简体   繁体   English

使用Java dom解析器进行XML解析可将xml声明转换为元素

[英]XML parsing with java dom parser converts xml declaration into elements

Here is the xml file that I need to process as part of my assignment. 这是我作为分配工作需要处理的xml文件。

<?xml-stylesheet type="text/xsl" href="people.xsl"?>
<People>
    <Person>
    `...`
    </Person>

    `...` 
</People>

I am using the "javax.xml.parsers.DocumentBuilderFactory" to create a dom parser. 我正在使用“ javax.xml.parsers.DocumentBuilderFactory”创建一个dom解析器。 After parsing, the resultant document does not have People at the root but some root having children as xml-stylesheet and People. 解析后,生成的文档的根目录不包含People,但某些根目录具有xml-stylesheet和People子元素。

Looks like this can be avoided. 看起来这样可以避免。

<?xml-stylesheet ... ?> is not an XML declaration. <?xml-stylesheet ... ?>不是XML声明。 It is a Processing Instruction (PI), and the DOM spec says that a Document node may contain zero or more of them. 它是一个处理指令(PI),并且DOM规范说文档节点可能包含零个或多个。

One approach would be to code your application to deal appropriately with (eg ignore) an PI's in the Document node. 一种方法是对您的应用程序进行编码,以适当地处理(例如忽略)Document节点中的PI。 Alternatively, just use the Document node's documentElement attribute / getter to get the root Element directly. 或者,只需使用Document节点的documentElement属性/ getter直接获取根Element。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM