2010-01-07 617 views
22

我正在修復關於DocumentBuilder.parse的現有代碼上的錯誤。我有下面的代碼:DocumentBuilder.parse(InputStream)返回null

String theOutput; 
    theOutput = response.encodeURL(prefix + "/include/sampleForConversion.jsp?" + request.getQueryString(); 
    StreamSource xmlSource = new StreamSource(new URL(theOutput).openStream(), "http://sampleApps.net/static/dataDef1.1.dtd");           
    Document xmlDoc = dBuilder.parse(xmlSource.getInputStream()); 

我不明白爲什麼我對xmlDoc中得到一個空值,雖然我有theOutput和xmlSource變量有效值。請幫忙。

謝謝!

+2

只是爲了說明:你有'(xmlDoc == null)= true'還是你得到一個空文件('[[#document:null]')?解析方法應該返回一個文檔或拋出一個異常,但永遠不會返回'null' ... – 2010-01-07 08:39:26

+0

hi Adreas, 我得到[#document:null] – 2010-01-07 08:53:30

+10

'[#document:null]'不代表空文檔,這只是'Document'的'toString()'輸出寫得很糟糕。 – skaffman 2010-01-07 09:57:41

回答

40

流很有可能已被解析正確,只是因爲 xmlDoc.toString()將始終爲"[#document: null]"。這並不表示,DOM樹是空的。請首先檢查,如果文件有一些節點(孩子)。

如果DOM確實是空的,那麼我首先將輸入流的內容打印到控制檯(可能xmlSource.getInputStream().toString()已經返回內容)以檢查內容是否格式正確,然後仔細檢查dtd文件是可訪問的(瀏覽器),最後,將XML文檔和dtd轉儲到文件中以檢查XML內容是否有效。

啊,等一下,我想第二個參數是DTD文件的URI,但是這個字符串是xml文檔的systemId(public StreamSource(InputStream inputStream, String systemId))。也許這是一個問題 - StreamSource類將使用這個URI來解析相對URI(比如你的DTD)。

+0

這種方法會在這些情況下返回null還是拋出異常? 'DocumentBuilder.parse(InputStream的)' – 2016-06-06 20:49:35