[英]Converting XML to document in java creates null document
我正在嘗試從此處(stackoverflow)和其他來源解析示例,這些示例是從java網上從網上下載的xml。
首先,我將xml打包在字符串中:
String xml = getXML(url, logger);
如果我此時打印出xml字符串:
System.out.println("XML " + xml);
我得到了xml的打印輸出,因此我假設到目前為止沒有故障。 然后,我嘗試創建一個可以評估的文檔:
InputSource is= new InputSource(new StringReader(xml));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
如果我在這里打印文檔:
System.out.println("Doc: " + doc);
我得到:文件:[#document:null]
當我稍后嘗試使用Xpath評估表達式時,我得到了java.lang.NullPointerException,並且在嘗試獲取根的長度時也得到了:
System.out.println("Root length " + rootNode.getLength());
這讓我相信文檔(以及后來的節點)確實為空。
當我嘗試打印輸入源或節點時,我得到例如。
輸入源:org.xml.sax.InputSource@29453f44
我不知道該怎么解釋。
誰能看到我做錯了什么或提出前進的方向嗎? 提前致謝。
您可能需要另一種方式將文檔呈現為字符串。
對於JDOM :
public static String toString(final Document document) {
try {
final ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
final XMLOutputter outp = new XMLOutputter();
outp.output(document, out);
final String string = out.toString("UTF-8");
return string;
}
catch (final Exception e) {
throw new IllegalStateException("Cannot stringify document.", e);
}
}
輸出
org.xml.sax.InputSource@29453f44
只是類名+實例的哈希碼(在Object類中定義)。 它指示實例的類具有未重寫的toString。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.