Non-obvious XPath: Getting elements that do not have a particular attribute or child element

Well sounds pretty simple.. Here's an example. Consider the following source XML document



<?xml version="1.0"?>
<Wizards>
<Wizard Name="Merlin" Level="5">
<Spells>
<Spell Name="SkinOfOil"/>
</Spells>
</Wizard>
<Wizard Name="Apprentice">
<Spells/>
</Wizard>
</Wizards>



So now to select all Wizards that do not have a Level attribute...



/Wizards/Wizard[not(@Level)]


Similarly to select all Wizards that do not know any Spells...



/Wizards/Wizard[not(Spells/Spell)]


The key here is the not function which reduces the argument to a boolean value. Once again XPath amazes me with its simplicity

No comments:

Post a Comment