Some interesting XPath queries

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

I heard from people that XPath is not that easy (although I am having trouble believing it… it seems easy enough), so when I wrote a couple of XPath queries last time I chose to blog them to make it easy for some of those people reading this blog.

Here are a couple:

How would you select a parent based on a value of it’s child?

XML:

<a>
    <b>
        <c value=”1″></c>
    </b>
    <b>
        <c value=”2″></c>
    </b>
    <b>
        <c value=”3″></c>
    </b>
</a>

XPath:

//b[descendant::c[@value='3']]

It selects a “b” node based on an attribute value on it’s child “c” node

How would you select a node which has exactly one child node with a given attribute value?

XML:

<a>
    <b>
        <c value=”a”>1</c>
        <c value=”a”>2</c>
        <c value=”v”>2</c>
    </b>
    <b>
        <c value=”c”>2</c>
    </b>
</a>

XPath:

//b[count(c[@value='v']) = 1]

This selects all “b” nodes which have exactly one “c” node with an attribute “value” equal to “v”

 

Hope this helps someone!

Cheers!


Filed under: XML, XPath
Written on: 23 Apr 2008 ·

kick it on DotNetKicks.com

Leave a Reply