我想检查此示例 xml 文件是否存在属性 ID 以及它是否不为空:
<component
id="http://../EDYRA/prototype/TextEditor"
isUI="true"
name="TextEditor"
version="0.1">
<binding>
<dependencies>
<dependency language="javascript">
<url>https://../TextEditor.js</url>
</dependency>
</dependencies>
<constructor>
<code>new TextEditor();</code>
</constructor>
</binding>
</component>
我用 Java 编写了这个 XPath 查询:
XPathExpression expr = xpath.compile("//component[@id]/@id/text()");
Object result = expr.evaluate(file, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
resultsString += "Expression: //component[@id]/@id/text();
resultsString += " \r\nNode List: " + result.toString() + " \r\n Item: ";
resultsString += nodes.item(0) + " \r\n Length: ";
resultsString += nodes.getLength() + " \r\n\r\n\r\n";
file.getDocumentElement();
resultsString += "Attribute ->" + " : " + file.getDocumentElement().getAttribute("id");
我已经测试过了,不幸的是它返回了包含 0 个项目的列表:
表达式://component[@id]/@id/text()
节点列表:com.sun.org.apache.xml.internal.dtm.ref.DTMNodeList@4fe3c938
项目:空
长度:0
属性 -> http://../EDYRA/prototype/TextEditor
应该如何查看正确的查询以检查此属性是否存在并获取此属性的值?
编辑:
//component[@id] 也没有返回结果。看起来每个查询都不返回任何内容......
最佳答案
//component[@id]/@id/text()
属性不能有子节点,但在上面的表达式中,您想要选择任何选定的 id
属性的所有文本节点子节点。这个不正确的表达式将始终选择零个节点。
选择 XML 文档中所有 component
元素的所有 id
属性(具有值)的一个 XPath 表达式是:
//component/@id[string()]
如果您也将纯空白值视为“空”,请使用此 XPath 表达式:
//component/@id[normalize-space()]
关于java - 检查是否恰好存在节点的一个属性并在 XPAth 中返回该属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36814313/