Java 为什么 DocumentBuilder.parse() 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22990532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 19:50:30  来源:igfitidea点击:

Why is DocumentBuilder.parse() not working

javaxml

提问by Aheinlein

I have read several posts about how to use the DocumentBuilder.parse()function for getting a document object.

我已经阅读了几篇关于如何使用该DocumentBuilder.parse()函数获取文档对象的帖子。

Document document = builder.parse(new InputSource(new StringReader(xml)));

was returning [#document: null]which as I found does not necessarily mean it is empty. However, after inspecting it more, I have found that it is in fact empty.

正在返回[#document: null],我发现这并不一定意味着它是空的。然而,我多看几眼,发现里面其实是空的。

I am building the String xml and have used an xml validator, (and pasted into eclipse and ctrl+shift+fto format it. This is usually my first try to see if something is well formed) to show it is valid xml. I decided to break out each part of the parse()parameters so I could step through and watch to make sure they were working correctly.

我建立字符串XML和已经使用了XML验证,(并粘贴到Eclipse和ctrl+ shift+f格式化。这通常是我第一次尝试看看是否有良好形成的),以显示它是有效的XML。我决定分解parse()参数的每个部分,以便我可以逐步检查并观察以确保它们正常工作。

My code is:

我的代码是:

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 and is appear to work correctly until I execute the builder.parse(is) line. 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? This has been driving me crazy, any input would be great!

sr 并且在我执行 builder.parse(is) 行之前似乎可以正常工作。一旦执行,sr.str 值变为 null 并与 is.characterInputStream.str 相同。这对我来说似乎很奇怪,这是预期的吗?这让我发疯了,任何输入都会很棒!

edit- my xml string is:

编辑-我的 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>

采纳答案by Jon Skeet

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?

一旦执行,sr.str 值变为 null 并与 is.characterInputStream.str 相同。这对我来说似乎很奇怪,这是预期的吗?

Yes, I'd say so. DocumentBuilder.parseis closing the reader. StringReader.close()sets strto null. This is an implementation detail of StringReader- but you should expectto see implementation details when you poke around private fields when debugging. (It's also not documented that DocumentBuilder.parsewill close the input it's given, but it seems reasonable.)

是的,我会这么说。DocumentBuilder.parse正在关闭阅读器。StringReader.close()设置strnull. 这是一个实现细节StringReader- 但是当您在调试时查看私有字段时,您应该期望看到实现细节。(它也没有记录DocumentBuilder.parse将关闭它给出的输入,但它似乎是合理的。)

It's unclear what the problem iswith your XML, but this part of the behaviour is entirely reasonable.

目前还不清楚什么问题你的XML,但这种行为的部分是完全合理的。

I would strongly recommend that you try your code with the simplest XML you can think of, e.g. "<foo />".

我强烈建议您使用您能想到的最简单的 XML 来尝试您的代码,例如"<foo />".

The code you've shown so far is fine. Here's a short but complete program to show it working:

到目前为止您显示的代码很好。这是一个简短但完整的程序来显示它的工作:

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());
   }
}