How to read XML response from a URL in java?
For xml parsing of an inputstream you can do:
// the SAX way:
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(handler);
myReader.parse(new InputSource(new URL(url).openStream()));
// or if you prefer DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());
But to communicate over http from server to client I prefer using hessian library or springs http invoker lib
Reading XML file from URL in java
xyou can try like this,
Here you can set your string response ang get xml string response into XML Document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document doc;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse(new InputSource( new StringReader("your xml string response")));
} catch (ParserConfigurationException | SAXException | IOException ex) {
ex.printStackTrace();
}
i'm not sure but i think it's helpful to you.
parsing XML from URL in java
By default, the URL returns data in JSON format. You see an XML in the browser because the way the browser negotiates a return type (via Accept header).
You can either parse the data as JSON, or change the URL to http://api.nbp.pl/api/exchangerates/rates/c/gbp/2015-01-01/2015-01-31?format=xml
.
Notice ?format=xml
at the end.
See the User manual.
Reading XML online and Storing It (Using Java)
Very simply:
File myOutput = new File("c:\\myDirectory\\myOutput.xml");
xform.transform(new DOMSource(doc), new StreamResult(myOutput));
How to Read XML Response using Java
I never work on XML parsing but when I debug your Code in my machine I got an error something like,
[Fatal Error] :1:84: The markup in the document following the root element must be well-formed.
Exception in thread "main" org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 84; The markup in the document following the root element must be well-formed.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:257)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
at com.flotomate.fd.system.etc.OprUtility.main(OprUtility.java:87)
and search on StackOverflow what cause I got an error I find this Answer
issue is not root element Added.
after I add root element still not fix. so I follow pattern same as Answer
not Sure optimize and well define but working
String response = " <root>"
+" <Response> "
+ " <NO>1</NO> "
+ " <NAME>John Doe</NAME> "
+ " </Response> "
+ " <Response> "
+ " <NO>2</NO> "
+ " <NAME>Jane Doe</NAME> "
+ " </Response> "
+ "</root>";
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
new InputSource(new StringReader(response.toString())));
NodeList nodeList = document.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
if (element.getNodeName().contains("Response")) {
System.out.println(element.getElementsByTagName("NO").item(0).getTextContent());
System.out.println(element.getElementsByTagName("NAME").item(0).getTextContent());
}
}
}
//And from this also.....
for (int i = 0; i < nodeList.getLength(); i++) {
Element element1 = (Element) nodeList.item(i);
System.out.println(element.getElementsByTagName("NO").item(0).getTextContent());
System.out.println(element.getElementsByTagName("NAME").item(0).getTextContent());
}
output:
1
John Doe
2
Jane Doe
HttpUrlConnection: how to get the XML response into a String?
I have two observations.
Move
connection.disconnect();
towards the end, where you are done with reading i.e. after thebr.close();
line.Follow Below sequence:
InputStream stream = connection.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream );
//put output stream into a string
BufferedReader br = new BufferedReader(isReader );
Hope that works!
Related Topics
Java.Lang.Noclassdeffounderror: Org/Hamcrest/Selfdescribing
Java: What's the Big-O Time of Declaring an Array of Size N
How to Change Timezone for a Java.Util.Calendar/Date
Jtable How to Change Background Color
Is There a MACro Recorder for Eclipse
Java Fileoutputstream Create File If Not Exists
In Java, How to Get the Difference in Seconds Between 2 Dates
How to Use Parameters, Request and Session Objects Present in Actioncontext
Apache PDFbox: Problems with Encoding
Tomcat 8 Is Not Able to Handle Get Request with '|' in Query Parameters
Using Java Map for Range Searches
In Java 8, Is There a Bytestream Class
How to Call a Method in Another Class of the Same Package
Java, How to Implement a Shift Cipher (Caesar Cipher)
How to Resize Jlabel Imageicon