132

Given the following XML, how do I write an XPath query to pull nodes where the attribute foo exists?:

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

3 Answers 3

213

Short and sweet:

//*[@foo]

Of course you should use a more specific expression. But with [@attributeName] you get all nodes which have that attribute.

0
40

Use the following XPath expression

//*[boolean(@foo)]
1
  • This was helpful in the case where it was part of a larger boolean expression, i.e. //button[@id='foo' and boolean(@disabled)] Oct 26, 2022 at 20:12
10

If you use and xpath, this maybe can help you:

count(//*[@foo])

it will return count of node/child that have attribute foo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.