[英]How to Read XML Document from URL
嗨,我正在使用文檔類。 當我從本地系統讀取File時,它正在工作;當我想讀取該文件,並嘗試從某個URL加載XML Document時,它不起作用。
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);
}
因此,如果我有一個返回xml的服務,並且想使用它,該方法將返回Document,我該怎么做呢?我想直接從服務GET URL加載。
我嘗試了這個但它不起作用
File file = new File("http://someservice/getdata");
錯誤:找不到文件然后我嘗試從Input Stream加載它,但對我來說也不起作用。
InputStream input = new URL("http://someurl:32643/api/values").openStream();
錯誤:
[Fatal Error] :1:1: Content is not allowed in prolog.
現在,我將如何實現此任何幫助將不勝感激,我想加載從服務接收的數據,並希望在我返回方法時返回該文檔。
以下代碼對我有用。
TestXML.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 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>
您實際上是否需要/使用xmlns屬性?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.