简体   繁体   English

如何使用Java从URL读取/获取XML文件?

[英]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. 我想从URL读取XML文件,然后解析它。 How can I do this in Java?? 如何在Java中执行此操作?

Reading from a URL is know different than any other input source. 从URL读取与任何其他输入源不同。 There are several different Java tools for XML parsing. 有几种用于XML解析的Java工具。

You can use Xstream it supports this. 您可以使用Xstream支持此功能。

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. 为此创建一个合适的XML源,甚至可能是一个Transformer。

Connect the two and get eg a DOM for further processing. 连接两者并获得例如DOM进行进一步处理。

I use JDOM: 我使用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. 当然,您可以将整个读取的URL剪切为字符串,然后将字符串读取器放在字符串上,但是Ive从两个不同的区域进行了剪切/粘贴。 So this was easier. 所以这更容易。

This is a good candidate for using Streaming parser : StAX StAX was designed to deal with XML streams serially; 这是使用Streaming解析器的一个很好的候选者: StAX StAX被设计为串行处理XML流。 than compared to DOM APIs that needs entire document model at one shot. 相比之下,需要一次性完成整个文档模型的DOM API相比。 StAX also assumes that the contents are dynamic and the nature of XML is not really known. StAX还假定内容是动态的,并且XML的本质并未真正为人所知。 StAX use cases comprise of processing pipeline as well. StAX用例也包括处理管道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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