XPath:如何检查属性是否存在?


104

给定以下XML,我该如何编写XPath查询来提取foo存在该属性的节点?:

<node1>
  <node2>
    <node3 foo='bar'></node3>
    <node3></node3>
    <node3 bar='foo'></node3>
    <node3 foo='foobar'></node3>
  </node2>
</node1>

Answers:


163

简短而甜美:

//*[@foo]

当然,您应该使用更具体的表达式。但是随着[@attributeName]获得所有具有该属性的节点。


25

使用以下XPath表达式

//*[boolean(@foo)]

8

如果使用xpath,这可能会帮助您:

count(//*[@foo])

它将返回具有属性foo的节点/子节点的计数

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.