我已经阅读了几篇关于如何使用该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());
   }
}
| 归档时间: | 
 | 
| 查看次数: | 13846 次 | 
| 最近记录: |