Reading XML drom webpage returning null - java

I am using following code to read XML from webpage. I have mentioned public URL here as cant mention project URL:
`String g1="http://www.w3schools.com/xml/note.xml";
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder=dbFactory.newDocumentBuilder();
Document doc=dBuilder.parse(g1);`
but I am receiving value of doc as null.

Do something like :-
String urlString = "http://www.w3schools.com/xml/note.xml";
URL url = new URL(urlString);
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder=dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(url.openStream());
NodeList descNodes = doc.getElementsByTagName("note");
for(int i=0; i<descNodes.getLength();i++)
{
System.out.println(descNodes.item(i).getTextContent());
}
Output:-
Tove
Jani
Reminder
Don't forget me this weekend!

Refer below link hope it helps you..see the part for 1.2 in it !!
http://viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/

Related

Protocol error trying to parse XML response in Java

I am successfully making an API call that is a SOAP request with an account number in the body. I connected using Httpurlconnection and I am reading those results using BufferedReader:
if (responseCode == HttpURLConnection.HTTP_OK) {​​​​​ // success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {​​​​​
{​​​​​
sb.append(inputLine).append("\n");
String xml2String = sb.toString();
Then using documentbuilderfactory to build the doc to read into the parser:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
Document xmlDom = docBuilder.parse(new InputSource(inputLine));
And then try to parse:
DOMParser parser = new DOMParser();
parser.parse(new InputSource(new StringReader(returnList.item(0).getTextContent())));
Document doc = parser.getDocument();
NodeList responsedata = doc.getDocumentElement().getChildNodes();
NodeList returnList = xmlDom.getElementsByTagName("DATA");
// Get the DATA
DOMParser parser = new DOMParser();
parser.parse(new InputSource(new StringReader(returnList.item(0).getTextContent())));
Document doc = parser.getDocument();
NodeList responsedata = doc.getDocumentElement().getChildNodes();
This is the error I get (which includes the output from the API request):
Exception,no protocol:
{​​​​​"d":"<DATA><BussFlds><FieldName>FirstName</FieldName><Value><![CDATA[TESTY]]></Value><DataType>String</DataType><Format></Format><Editable>True</Editable></BussFlds><BussFlds><FieldName>LastName</FieldName><Value><![CDATA[TESTER]]></Value><DataType>String</DataType><Format></Format><Editable>True</Editable></BussFlds><BussFlds><FieldName>TYPE</FieldName><Value><![CDATA[]]></Value><DataType>String</DataType><Format></Format><Editable>True</Editable></BussFlds><BussFlds><FieldName>DATE</FieldName><Value><![CDATA[]]></Value><DataType>String</DataType><Format></Format><Editable>True</Editable></BussFlds><BussFlds><FieldName>CUSTCODE</FieldName><Value><![CDATA[]]></Value><DataType>String</DataType><Format></Format><Editable>True</Editable></BussFlds><BussFlds><FieldName>PREMCODE</FieldName><Value><![CDATA[]]></Value><DataType>String</DataType><Format></Format><Editable>True</Editable></BussFlds><BussFlds><FieldName>ADDRESS</FieldName><Value><![CDATA[]]></Value><DataType>String</DataType><Format></Format><Editable>True</Editable></BussFlds><BussFlds><FieldName>CITY</FieldName><Value><![CDATA[]]></Value><DataType>String</DataType><Format></Format><Editable>True</Editable></BussFlds><BussFlds><FieldName>STATE</FieldName><Value><![CDATA[]]></Value><DataType>String</DataType><Format></Format><Editable>True</Editable></BussFlds><BussFlds><FieldName>ZIP</FieldName><Value><![CDATA[]]></Value><DataType>String</DataType><Format></Format><Editable>True</Editable></BussFlds><BussFlds><FieldName>ZIP4</FieldName><Value><![CDATA[]]></Value><DataType>String</DataType><Format></Format><Editable>True</Editable></BussFlds><BussFlds><FieldName>ACCTBALANCE</FieldName><Value><![CDATA[]]></Value><DataType>String</DataType><Format></Format><Editable>True</Editable></BussFlds><BussFlds><FieldName>PASTDUE</FieldName><Value><![CDATA[]]></Value><DataType>String</DataType><Format></Format><Editable>True</Editable></BussFlds><BussFlds><FieldName>PHONE</FieldName><Value><![CDATA[]]></Value><DataType>String</DataType><Format></Format><Editable>True</Editable></BussFlds></DATA>"}​​​​​
I suspect that it is that curly bracket data on the first row or missing header information but I am not sure if that is the issue or how to fix it. Thanks!
In
docBuilder.parse(new InputSource(inputLine))
You are using the stringbuffer. Replace it with your variable xml2String
This response:
{"d":"<DATA><BussFlds>…
is not XML. You cannot read it with a DocumentBuilder.
That response is in a format known as JSON. You cannot use an XML parser to read it.
So, you will want to pass the response to a JSON parser, not an XML parser.
A JSON “object” is basically a dictionary (that is, a lookup table) with string keys. Your response has exactly one entry, whose key is "d". So you first need to parse the response as JSON:
String xml;
try (JsonParser jsonParser = Json.createParser(con.getInputStream())) {
xml = jsonParser.getObject().getString("d");
}
(There are other JSON parsing libraries available. I chose the one that is part of Java EE for the above example.)
Notice that the code does not attempt to read con.getInputStream() as a string first. There is no benefit to doing that. The parser accepts an InputStream directly. Which means there is no need to use InputStreamReader, or BufferedReader, or StringBuffer.
Now that you have XML content in the xml variable, you can parse it with DocumentBuilder:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
Document xmlDom = docBuilder.parse(new InputSource(new StringReader(xml)));
Side note: You should never use StringBuffer. Use StringBuilder instead. StringBuffer is a 26-year-old class that was part of Java 1.0, and it is designed for multithreaded use, which is almost never needed, and which adds a lot of overhead.

how to parse and get data from xml in java

I have this XML code:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="https://www.cvlkra.com/">tTKyEndh0iBqnZdjpUntEQ%3d%3d</string>
I want to get this: tTKyEndh0iBqnZdjpUntEQ%3d%3d for which I have tried the below code:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder1 = factory.newDocumentBuilder();
Document document = builder1.parse(new InputSource(new StringReader(string)));
Element rootElement = document.getDocumentElement();
String nodeName = rootElement.getNodeName();
But i am not getting it. I am getting null value instead of tTKyEndh0iBqnZdjpUntEQ%3d%3d even when I have tried some other code also.
Try using getTextContent() instead getNodeValue() returns null because it has no values.
You should not use getNodeName() instead use rootElement.getNodeValue(). May be this helps.

Need help parsing XML file for Twitter Oauth

I've written a twitter desktop app that basically just lets me post tweets and pics... nothing fancy.
I've got everything working but this last part of persisting a config file (which is the following XML generated by my application.
<?xml version="1.0" encoding="UTF-8" standalone="no"?><Twitterer><config id="1"><accessToken>ENDLESS-STRING-OF-CHARACTERS</accessToken><accessTokenSecret>ANOTHER-ENDLESS-STRING-OF-CHARACTERS</accessTokenSecret></config></Twitterer>
What I need to do is just set the accessToken & accessTokenSecret variables. The filename is config.xml.
I've been looking at a lot of examples on the net, but can't seem to wrap my head around only getting two values from the file, which shouldn't need a loop.
This is as far as I've gotten on this last piece of my puzzle:
try {
File fXmlFile = new File(this.getFileName());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("config");
int numberOfConfigs = nList.getLength();
// GET THE TWO VARIABLES HERE
} catch (Exception e) {
}
If anyone can help me just read those two tags into their corresponding variables I would be quite appreciative. I can handle the rest of the Authorization after that.
What I need to do is just set the accessToken & accessTokenSecret variables
A simple code using getElementsByTagName() method
Element root = doc.getDocumentElement();
root.getElementsByTagName("accessToken").item(0).getTextContent()
root.getElementsByTagName("accessTokenSecret").item(0).getTextContent()
output:
ENDLESS-STRING-OF-CHARACTERS
ANOTHER-ENDLESS-STRING-OF-CHARACTERS
OR try as child node of config tag
Element root = doc.getDocumentElement();
NodeList configNodeList = root.getElementsByTagName("config");
NodeList nodeList = ((Node) configNodeList.item(0)).getChildNodes();
System.out.println(nodeList.item(0).getTextContent());
System.out.println(nodeList.item(1).getTextContent());

Parsing XML using XPath in Java using Google Geocode

kohaNimi = "Tallinn";
URL myUrl = new URL("http://maps.googleapis.com/maps/api/geocode/xml?address=" + kohaNimi + "&sensor=false");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(myUrl.openStream());
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/GeocodeResponse/result/bounds/southwest/lat");
String swLat = expr.evaluate(doc, XPathConstants.STRING).toString();
System.out.println("swLat: " + swLat );
So I am trying to use Google geocode API to get the coordinates of a town, but I have trouble parsing the xml. I am trying to use xPath with Java. I can verify that ... does exist. The problem is that when I try to parse this xml I wont get any text as response. I have looked over the code and can't seem to figure out what is wrong. I used this blogpost to assemble my code: http://tunatore.wordpress.com/2011/05/20/how-to-use-xpath-i-java-simple-example/
You can verify that xpath is correct(should get response) from here: http://maps.googleapis.com/maps/api/geocode/xml?address=Tallinn&sensor=false
Can anyone spot what is wrong?
Change:
xpath.compile("/GeocodeResponse/result/bounds/southwest/lat")
To:
xpath.compile("/GeocodeResponse/result/geometry/bounds/southwest/lat")

Use a Remote XML as File [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to read XML response from a URL in java?
I'm trying to read an XML file from my web server and display the contents of it on a ListView, so I'm reading the file like this:
File xml = new File("http://example.com/feed.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xml);
doc.getDocumentElement().normalize();
NodeList mainNode = doc.getElementsByTagName("article");
// for loop to populate the list...
The problem is that I'm getting this error:
java.io.FileNotFoundException: /http:/mydomainname.com/feed.xml (No such file or directory)
Why I'm having this problem and how to correct it?
File is meant to point to local files.
If you want to point to a remote URI, the easiest is to use the class url
//modified code
URL url = new URL("http://example.com/feed.xml");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
//your code
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse( in );
As you can see, later on, thanks to java streaming apis, you can easily adapt your code logic to work with the content of the file. This is due to an overload of the parse method in class DocumentBuilder.
You need to use HTTPURLConnection to get xml as input stream and pass it DocumentBuilder, from there you can use the logic you have.
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(yourURL);
if(resp.getStatusCode == 200)
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(resp.getEntity().getContent());
}
Note: I just type here, there may be syntax errors.
You need to read the file using a URL object. For instance, try something like this:
URL facultyURL = new URL("http://example.com/feed.xml");
InputStream is = facultyURL.openStream();

Categories