XPath: How to check if an attribute exists?

XmlXpath

Xml Problem Overview


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>

Xml Solutions


Solution 1 - Xml

Short and sweet:

//*[@foo]

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

Solution 2 - Xml

Use the following XPath expression

//*[boolean(@foo)]

Solution 3 - Xml

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

count(//*[@foo])

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionByron WhitlockView Question on Stackoverflow
Solution 1 - XmlFelix KlingView Answer on Stackoverflow
Solution 2 - XmlRu5View Answer on Stackoverflow
Solution 3 - XmlfritzView Answer on Stackoverflow