[英]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.