'How to filter with XPath on all elements without a specific attribute
My XPath is a little bit rusty... Let's say I have this simple XML file:
<?xml version="1.0" encoding="utf-8" ?>
<States xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<States>
<StateProvince name="ALABAMA" abbrev="AL" />
....
<StateProvince name="AMERICAN SAMOA" abbrev="AS" territory="true" />
</States>
</States>
I would like to run a simple XPath query to parse out all of the true states (so don't pull in states where territory = true). I tried \StateProvince[@territory!='true'] but I got zero. Other variations seem to be failing. This seems like it should be simple, but not finding what I want.
Any help appreciated.
Solution 1:[1]
You are very close:
//StateProvince[not(@territory) or @territory != 'true']
Should get you the result you want.
Solution 2:[2]
This should work:
//StateProvince[not(@territory='true')]
Solution 3:[3]
To find the nodes that don't have any territory attributes whatsoever:
/States/States/StateProvince[not(@territory)]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jordan S. Jones |
| Solution 2 | pgb |
| Solution 3 | dan-gph |
