Java DocumentBuilder.parse(InputStream) 返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2018868/
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
DocumentBuilder.parse(InputStream) returns null
提问by Pink Angel
I am fixing a bug on an existing code concerning DocumentBuilder.parse. I have the below code:
我正在修复有关 DocumentBuilder.parse 的现有代码的错误。我有以下代码:
String theOutput;
theOutput = response.encodeURL(prefix + "/include/sampleForConversion.jsp?" + request.getQueryString();
StreamSource xmlSource = new StreamSource(new URL(theOutput).openStream(), "http://sampleApps.net/static/dataDef1.1.dtd");
Document xmlDoc = dBuilder.parse(xmlSource.getInputStream());
I dont understand why i am getting a null value for xmlDoc though I have valid values for theOutput and xmlSource variables. Please help.
我不明白为什么我得到 xmlDoc 的空值,尽管我有 theOutput 和 xmlSource 变量的有效值。请帮忙。
thanks!
谢谢!
采纳答案by Andreas Dolk
There is a good chance that the stream has been parsed correct, just because
xmlDoc.toString()
will always be "[#document: null]"
. This doesn't indicate, that the DOM tree is empty. Please check first, if the document has some nodes (children).
有一个很好的机会,流已被解析正确的,只是因为
xmlDoc.toString()
总是会"[#document: null]"
。这并不表示 DOM 树是空的。请先检查文档是否有一些节点(子节点)。
If the DOM really was empty, then I'd first print the content of the input stream to the console (maybe xmlSource.getInputStream().toString()
already return the content) to check if the content is well-formed, double-check if the dtd file was accessible (browser) and finally, dump the XML document and the dtd into files to check if the XML content is valid.
如果 DOM 真的是空的,那么我首先将输入流的内容打印到控制台(可能xmlSource.getInputStream().toString()
已经返回内容)以检查内容是否格式正确,仔细检查 dtd 文件是否可访问(浏览器) 最后,将 XML 文档和 dtd 转储到文件中以检查 XML 内容是否有效。
Ahh, wait a second, I thought the second parameter was the URI of the DTD file, but the string is the systemId of the xml document (public StreamSource(InputStream inputStream, String systemId)
). Maybe that's a problem - the StreamSource class will use this URI to resolve relative URIs (like your DTD).
啊,等一下,我以为第二个参数是DTD文件的URI,其实字符串是xml文档的systemId( public StreamSource(InputStream inputStream, String systemId)
)。也许这是一个问题 - StreamSource 类将使用此 URI 来解析相对 URI(如您的 DTD)。