2014-03-18 71 views
1

嗨,我正在處理文檔類。當我從本地系統讀取文件時,它正在工作,當我想讀取該文件並嘗試從某個URL加載XML文檔時,它無法工作。如何從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); 
} 

所以,如果我有返回XML服務,我想使用它我怎麼能做到這一點我想直接從服務中獲得URL加載該方法返回文檔。

我試着用這個,但它不工作

File file = new File("http://someservice/getdata"); 

錯誤:未找到文件 然後我試圖從輸入加載流時,也沒有從我的工作。

InputStream input = new URL("http://someurl:32643/api/values").openStream(); 

錯誤:

[Fatal Error] :1:1: Content is not allowed in prolog. 

現在,我怎麼能做到這一點的任何幫助將不勝感激我想加載從服務接收到的數據,並希望返回的一個文件,我在我回國我的方法。

+0

你正在加載的文件是什麼樣的? –

+0

其實際上是一個XML – Adam

+0

我明白這一點。它是什麼樣子的。 –

回答

1

以下代碼適用於我。

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雖然屬性?