131

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>
kjhughes
  • 106,133
  • 27
  • 181
  • 240
Byron Whitlock
  • 52,691
  • 28
  • 123
  • 168

3 Answers3

211

Short and sweet:

//*[@foo]

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

ulidtko
  • 14,740
  • 10
  • 56
  • 88
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
40

Use the following XPath expression

//*[boolean(@foo)]
ulidtko
  • 14,740
  • 10
  • 56
  • 88
Ru5
  • 821
  • 9
  • 6
  • This was helpful in the case where it was part of a larger boolean expression, i.e. `//button[@id='foo' and boolean(@disabled)]` – jewbix.cube Oct 26 '22 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

ulidtko
  • 14,740
  • 10
  • 56
  • 88
fritz
  • 121
  • 4