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.
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.
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".
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.
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.
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
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With