[英]Why is DocumentBuilder.parse() not working
我已經閱讀了幾篇關於如何使用DocumentBuilder.parse()
函數獲取文檔對象的帖子。
Document document = builder.parse(new InputSource(new StringReader(xml)));
正在返回[#document: null]
,我發現並不一定意味着它是空的。 然而,經過更多的檢查,我發現它實際上是空的。
我正在構建String xml並使用了一個xml驗證器,(並粘貼到eclipse和ctrl + shift + f來格式化它。這通常是我第一次嘗試查看是否有一些形式正確)來表明它是有效的xml。 我決定打破parse()
參數的每一部分,這樣我就可以單步執行並觀察以確保它們正常工作。
我的代碼是:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
StringReader sr = new StringReader(xml);
InputSource is = new InputSource(sr);
Document document = builder.parse(is);
return document;
} catch(Exception e){
e.printStackTrace();
}
sr和似乎正常工作,直到我執行builder.parse(是)行。 執行此操作后,sr.str值將變為null,與is.characterInputStream.str相同。 這對我來說很奇怪,這是預期的嗎? 這一直讓我發瘋,任何輸入都會很棒!
編輯 - 我的xml字符串是:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Feed Title</title>
<link>Feed Link</link>
<description>Feed Description</description>
<item>
<title>Item Title</title>
<link>Item Link</link>
<description>Item Description</description>
</item>
<item>
<title>Another Item</title>
<link>Another Link</link>
<description>Another Description</description>
</item>
</channel>
</rss>
執行此操作后,sr.str值將變為null,與is.characterInputStream.str相同。 這對我來說很奇怪,這是預期的嗎?
是的,我會這么說。 DocumentBuilder.parse
正在關閉讀者。 StringReader.close()
將str
設置為null
。 這是StringReader
一個實現細節 - 但是當您在調試時查看私有字段時,您應該會看到實現細節。 (也沒有記錄DocumentBuilder.parse
將關閉它給出的輸入,但它似乎是合理的。)
目前還不清楚該問題是否與你的XML是什么,但行為的這部分是完全合理的。
我強烈建議您使用您能想到的最簡單的XML來嘗試您的代碼,例如"<foo />"
。
你到目前為止所展示的代碼很好。 這是一個簡短但完整的程序,用於顯示它的工作情況:
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import java.io.*;
class Test {
public static void main(String [] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
StringReader sr = new StringReader("<foo />");
InputSource is = new InputSource(sr);
Document document = builder.parse(is);
System.out.println(document.getDocumentElement().getTagName());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.