简体   繁体   中英

how to read/fetch the XML file from an URL using Java?

I want to read an XML file from an URL and I want to parse it. How can I do this in Java??

Reading from a URL is know different than any other input source. There are several different Java tools for XML parsing.

You can use Xstream it supports this.

URL url = new URL("yoururl");
BufferedReader in = new BufferedReader(
                new InputStreamReader(
                url.openStream()));



xSteamObj.fromXML(in);//return parsed object

Two steps:

  1. Get the bytes from the server.
  2. Create a suitable XML source for it, perhaps even a Transformer.

Connect the two and get eg a DOM for further processing.

I use JDOM:

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.*;

StringBuilder responseBuilder = new StringBuilder();
try {
 // Create a URLConnection object for a URL
 URL url = new URL( "http://127.0.0.1" );
 URLConnection conn = url.openConnection();
 HttpURLConnection httpConn;

 httpConn = (HttpURLConnection)conn;
 BufferedReader rd = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
 String line;

 while ((line = rd.readLine()) != null)
 {
  responseBuilder.append(line + '\n');
 }
}
catch(Exception e){
 System.out.println(e);
}

SAXBuilder sb = new SAXBuilder();
Document d = null;
try{
    d = sb.build( new StringReader( responseBuilder.toString() ) );
}catch(Exception e){
    System.out.println(e);
}

Of course, you can cut out the whole read URL to string, then put a string reader on the string, but Ive cut/pasted from two different areas. So this was easier.

This is a good candidate for using Streaming parser : StAX StAX was designed to deal with XML streams serially; than compared to DOM APIs that needs entire document model at one shot. StAX also assumes that the contents are dynamic and the nature of XML is not really known. StAX use cases comprise of processing pipeline as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM