Byron Whitlock
Byron Whitlock

Reputation: 53850

XPath: How to check if an attribute exists?

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>

Upvotes: 134

Views: 126431

Answers (3)

Ru5
Ru5

Reputation: 831

Use the following XPath expression

//*[boolean(@foo)]

Upvotes: 41

fritz
fritz

Reputation: 141

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

count(//*[@foo])

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

Upvotes: 12

Felix Kling
Felix Kling

Reputation: 816252

Short and sweet:

//*[@foo]

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

Upvotes: 217

Related Questions