gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:14:02 26 4
gpt4 key购买 nike

我想获取包含以下属性之一的每个子节点: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] didn't help either, as a result of that I got every node from the XML with one of the attributes but I want to get only the child nodes of the given node n

这是因为“//”会搜索整个文档。您的谓词是正确的,但您要过滤的序列是错误的。要获取上下文节点的子节点,请使用

*[@base or @ref or @type]

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

关于java - Java中如何使用XPath检查节点是否具有一个或多个特定属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11573869/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com