非命名空间感知 DOM 中的命名空间 XML 出现奇怪的 XPath 结果?

问题描述 投票:0回答:1

我的以下代码会导致意外结果:

        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader("""
                <ns:Msg xmlns:ns=\"abc\">
                    <ns:MsgType>
                        <ns:MsgType>TestType</ns:MsgType>
                    </ns:MsgType>
                    <ns:MsgType>
                        <ns:MsgType>TestType</ns:MsgType>
                    </ns:MsgType>
                </ns:Msg>
                """)));
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodelist = (NodeList) xPath.compile("//MsgType/MsgType").evaluate(document, XPathConstants.NODESET);
        nodelist.getLength(); // => 2 ok
        nodelist = (NodeList) xPath.compile("//MsgType").evaluate(document, XPathConstants.NODESET);
        nodelist.getLength(); // => 0 why?

//MsgType/MsgType
如何返回比
//MsgType
更多的节点?

DomBuildingFactoy
namespaceAware
默认属性默认设置为 false。 省略命名空间
ns
和命名空间声明一起返回预期结果:分别为 2 和 4。)

java xml xpath xml-namespaces
1个回答
2
投票

针对非命名空间感知的 DOM 运行 XPath 的效果是未定义的。 XPath 语言规范假定 XML 具有命名空间意识。当然,如果 DOM 是命名空间感知的,那么您需要编写 XPath 来考虑命名空间。

我同意观察到的效果令人惊讶,但我不认为这是一个错误。

© www.soinside.com 2019 - 2024. All rights reserved.