Showing posts with label XPath. Show all posts
Showing posts with label XPath. Show all posts

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

Non-obvious XPath: Getting an element by specifying it's value

This one took around half - an - hour out of my working day.
Problem:
I needed to get a specific element from an XML document based on its value / element content.
[Root]
[SomeSection]
[path]C:\Diablo II\[/path]
[path]H.G.Wells[/path]
[/SomeSection]
[Section2]
[path]Morlocks[/path]
[/Section2]
[/Root]

So I need a query to get me the element which has the text H.G.Wells. I could find a whole lot of examples on the net to get me an element based on the value of one of it's attribute.
e.g. /root/SomeSection[@attr='value']
or based on one of its sub elements
e.g. /root/SomeSection[path='H.G.Wells']
I tried a whole of things but to no avail. Then I turned to pester one of my buddies Ranjeet here, who turned to a saved ref document.

The answer here is
/root/SomeSection/path[.='H.G.Wells']
the dot was my missing link to the solution. Oh well, what the hell...
Here's hoping the next guy finds it sooner