开发者

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 e.g. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜