Java 如何从 URL 读取 XML 文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22487516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Read XML Document from URL
提问by
Hi I am working with Document Class. When I am reading File from local system it is working and when I want to read the file and try to load the XML Document from some URL its not working.
嗨,我正在使用文档类。当我从本地系统读取文件时,它正在工作,当我想读取文件并尝试从某个 URL 加载 XML 文档时,它不起作用。
private static Document loadTestDocument(String fileLocation) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder db = factory.newDocumentBuilder();
File file = new File(fileLocation);
System.out.println(db.parse(file).toString());
return db.parse(file);
}
So this method is returning Document if I have a service which returns xml and I want to consume it how can I do this I want to directly load from the service GET url.
因此,如果我有一个返回 xml 的服务并且我想使用它,则此方法将返回 Document,我该怎么做,我想直接从服务 GET url 加载。
I tried with this but its not working
我试过这个,但它不工作
File file = new File("http://someservice/getdata");
Error: File not found Then I tried to load it from Input Stream it also not working from me.
错误:找不到文件然后我尝试从输入流加载它,它也无法从我这里工作。
InputStream input = new URL("http://someurl:32643/api/values").openStream();
Error:
错误:
[Fatal Error] :1:1: Content is not allowed in prolog.
Now how can I achieve this any help will be appreciated I want to load the data received from the service and want to return a Document of that as I am returning in my method.
现在我如何实现这一点,任何帮助将不胜感激我想加载从服务接收到的数据,并希望在我的方法中返回时返回该文档。
采纳答案by Logan Murphy
The following code works for me.
以下代码对我有用。
TestXML.java
测试XML.java
import java.net.URL;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class TestXML {
private static Document loadTestDocument(String url) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
return factory.newDocumentBuilder().parse(new URL(url).openStream());
}
public static void main(String[] args) throws Exception {
Document doc = loadTestDocument("http://www.enetpulse.com/wp-content/uploads/sample_xml_feed_enetpulse_soccer.xml");
System.out.println(doc);
doc = loadTestDocument("http://localhost/array.xml");
System.out.println(doc);
}
}
array.xml
数组.xml
<?xml version="1.0"?>
<ArrayOfstring xmlns:i="w3.org/2001/XMLSchema-instance" xmlns="schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>
Do you actually need/use the xmlns attributes though?
你真的需要/使用 xmlns 属性吗?