Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read XML response from a URL in java?

I need to write a simple function that takes a URL and processes the response which is XML or JSON, I have checked the Sun website https://swingx-ws.dev.java.net/servlets/ProjectDocumentList , but the HttpRequest object is to be found nowhere, is it possible to do this in Java? I`m writting a rich client end app.

like image 830
Imran Avatar asked Feb 22 '10 10:02

Imran


People also ask

How do I read an XML string in Java?

In this article, you will learn three ways to read XML files as String in Java, first by using FileReader and BufferedReader, second by using DOM parser, and third by using open-source XML library jcabi-xml.

How do I read XML files?

If all you need to do is view the data in an XML file, you're in luck. Just about every browser can open an XML file. In Chrome, just open a new tab and drag the XML file over. Alternatively, right click on the XML file and hover over "Open with" then click "Chrome".

Which XML parser is fastest Java?

The design is inspired by the design of VTD-XML, the fastest XML parser for Java I have seen, being even faster than the StAX and SAX Java standard XML parsers.

Which of the following is an element used in read XML while trying to get the data form XML file?

We must have followed the process to read an XML file in Java: Instantiate XML file: DOM parser loads the XML file into memory and consider every tag as an element. Get root node: Document class provides the getDocumentElement() method to get the root node and the element of the XML file.


2 Answers

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

like image 74
Karussell Avatar answered Sep 21 '22 17:09

Karussell


If you want to print XML directly onto the screen you can use TransformerFactory

URL url = new URL(urlString); URLConnection conn = url.openConnection();  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(conn.getInputStream());  TransformerFactory transformerFactory= TransformerFactory.newInstance(); Transformer xform = transformerFactory.newTransformer();  // that’s the default xform; use a stylesheet to get a real one xform.transform(new DOMSource(doc), new StreamResult(System.out)); 
like image 21
thisisananth Avatar answered Sep 22 '22 17:09

thisisananth