繁体   English   中英

如何使用Java中的XPath检查节点是否具有一个或多个特定属性?

[英]How to check if node has one or more specific attributes with XPath in Java?

我想获取包含以下属性之一的每个子节点:type,ref,base。 每个属性的值都没有关系,我只想检查该属性是否存在。

我现在是这样的:

private void addRequiredNodeAndChildren(Node n) {    
            XPath xpath = XPathFactory.newInstance().newXPath();
            String expression = "*//*[@base or @ref or @type]";
            XPathExpression expr = xpath.compile(expression);
            NodeList referList = (NodeList) expr.evaluate(n, XPathConstants.NODESET);
            ..
}

该表达式可以正常工作,但在某些情况下,我无法获得所有预期的节点:

 <xs:complexType name="ListElement">
        <xs:annotation>
            <xs:documentation>
            </xs:documentation>
        </xs:annotation>
        <xs:attribute name="transferMode" type="myprefix:dataTransferMode"
            use="optional">
            <xs:annotation>
                <xs:documentation>Documentation for attribute
                </xs:documentation>
            </xs:annotation>
        </xs:attribute>
    </xs:complexType>

我希望得到上面表达式的节点,但是不幸的是我没有得到。 将表达式更改为

//*[@base or @ref or @type] 

也无济于事,结果是我从XML中获得每个带有一个属性的节点,但我只想获取给定节点n的子节点。 我也试过

*//*[@base] or *//*[@ref] or *//*[@type]

作为表达,但效果不佳。

有谁知道如何解决我的问题?

//*[@base or @ref or @type]也无济于事,因此我从XML的每个节点中获得了其中一个属性,但我只想获取给定节点n的子节点

那是因为'//'搜索整个文档。 您的谓词是正确的,但是您要过滤的顺序是错误的。 要获取上下文节点的子代,请使用

*[@base or @ref or @type]

顺便说一句,如果您试图在XSD中列出所有包含引用架构中其他声明的QName的属性,则您的列表是不完整的。

看来您想要的是:

*[descendant-or-self::*[@base or @ref or @type] ]

谢谢大家的帮助!

我找到了一个不是很漂亮的解决方案,但至少可以正常工作:

*[@base or @ref or @type] | *//*[@base or @ref or @type]

编辑:我改编了Dimitre Novatchev的解决方案,它也解决了这个问题:

descendant-or-self::*[@base or @ref or @type]

暂无
暂无

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

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