来自HTTP的XML解析文件 [英] XML parse file from HTTP
本文介绍了来自HTTP的XML解析文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的XML文件位于某个位置,例如
I have an XML file located at a location such as
http://example.com/test.xml
我正在尝试解析XML文件,以便在我的程序中使用xPath,但它是不工作。
I'm trying to parse the XML file to use it in my program with xPath like this but it is not working.
Document doc = builder.parse(new File(url));
如何获取XML文件?
推荐答案
尝试使用 URLConnection.getInputStream()
获取XML文件的句柄。
Try using URLConnection.getInputStream()
for getting the handle of XML file.
请参阅下面的代码,我试图打开一个xml文件并打印所有 description
字段:
See the below code, in that I am trying to open an xml file and printing all the description
fields:
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class HTTPXMLTest
{
public static void main(String[] args)
{
try {
new HTTPXMLTest().start();
} catch (Exception e) {
e.printStackTrace();
}
}
private void start() throws Exception
{
URL url = new URL("http://localhost:8080/AutoLogin/resource/web.xml");
URLConnection connection = url.openConnection();
Document doc = parseXML(connection.getInputStream());
NodeList descNodes = doc.getElementsByTagName("description");
for(int i=0; i<descNodes.getLength();i++)
{
System.out.println(descNodes.item(i).getTextContent());
}
}
private Document parseXML(InputStream stream)
throws Exception
{
DocumentBuilderFactory objDocumentBuilderFactory = null;
DocumentBuilder objDocumentBuilder = null;
Document doc = null;
try
{
objDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
objDocumentBuilder = objDocumentBuilderFactory.newDocumentBuilder();
doc = objDocumentBuilder.parse(stream);
}
catch(Exception ex)
{
throw ex;
}
return doc;
}
}
这篇关于来自HTTP的XML解析文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文