XPath: How to check if an attribute exists?

Byron Whitlock picture Byron Whitlock · Sep 17, 2010 · Viewed 89.9k times · Source

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>

Answer

Felix Kling picture Felix Kling · Sep 17, 2010

Short and sweet:

//*[@foo]

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