我已经阅读了几篇关于如何使用 DocumentBuilder.parse()
函数获取文档对象的文章。
Document document = builder.parse(new InputSource(new StringReader(xml)));
返回 [#document: null]
我发现这并不一定意味着它是空的。然而,在仔细检查之后,我发现它实际上是空的。
我正在构建 String xml 并使用了 xml validator ,(并粘贴到 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(is) 行之前似乎可以正常工作。一旦执行,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>
最佳答案
As soon as this executes, the sr.str value becomes null and same with is.characterInputStream.str. This seems odd to me, is this expected?
是的,我会这么说。 DocumentBuilder.parse
正在关闭阅读器。 StringReader.close()
套str
至 null
.这是 StringReader
的实现细节- 但您应该期望在调试时查看私有(private)字段时看到实现细节。 (也没有记录 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());
}
}
关于java - 为什么 DocumentBuilder.parse() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22990532/