Just a quick question as to the difference between xpath’s ‘not’ and ‘!=’ in the following content.
Taking the XML:
<years>
<year value="2010"></year>
<year value="2010"></year>
<year value="2010"></year>
<year value="2009"></year>
</years>
I want to select unique years. I have struggled for a while to achieve this, but managed in the end, but in a curious way that I did not expect.
The following xpath is correct for my intention and returns two unique year nodes of 2009 and 2010.
years/year[not(@value = preceding-sibling::year/@value)]
The following only returns the 2009 year node.
years/year[@value != preceding-sibling::year/@value]
The only difference between them is the != and not operators. I’ve pondered on this a while and I can’t find a difference that I could satisfactorily explain to anyone else.
Perhaps someone could help.
Cheers
Steve
The second example does not work because if you apply it to each of the first 3 nodes, it never matches. For the first
<year>, there’s no preceding sibling whose value one might try to compare to, so it fails to match. For the second and third, their preceding node does have the same value, so the non-equality test fails and leads to no match again.The
not(...)version works because in the first node, the whole@value = preceding-sibling::year/@valuefails due to the lack of a preceding sibling, and this failure in inverted bynot, giving you a match on the first node.