tags:

views:

497

answers:

2

Given a piece of Xml Like the one below. How would I write an XPATH Query to get the value of the 'leaf2' child where the 'key' value has a particular values (say 2)

I'm working in C# .NET. At the moment I'm just looking at getting the Xpath for key using SelectNodes , finding the right value then navigating back up to leaf2.

<root>
    <child>
        <anotherChild>
           <key>1</key>
        </anotherChild>
        <leaf1>X</leaf1>
        <leaf2>Y</leaf2>
        <leaf3></leaf3>
    </child>
    <child>
        <anotherChild>
           <key>2</key>
        </anotherChild>
        <leaf1>A</leaf1>
        <leaf2>B</leaf2>
        <leaf3></leaf3>
    </child>
</root>
+8  A: 

You want:

/root/child[anotherChild/key = '2']/leaf2

This is saying, "get elements named leaf2, whose parent is child and whose grandparent is root, where child is being filtered by its child named anotherChild with a child named key whose value is 2."

Welbog
Shouldn't it be key = '2' ?
Naveen
Right, right. Slipped my mind.
Welbog
+2  A: 

Or, perhaps a bit more flexibly because it doesn't assume the grandfather is root

//child/anotherChild/key[text()="2"]/../../leaf2

"find the key with text 2, parent anotherChild and grandparentchild, go to grandparent(i.e. child, and find leaf2"

Paul
this may well work too. I haven't tried it as yet.
TygerKrash
Should do. I tested it in SketchPath against your XML (so not actually in C#)
Paul
So, who marked this down, and would you mind saying why?
Paul