Link to home
Start Free TrialLog in
Avatar of YZlat
YZlatFlag for United States of America

asked on

Need help with XPath

I have an xml file with the following content
<Root>   
<Node>     
<SubEl1>abc</SubEl1>     
<SubEl2>def</SubEl2>     
<SubEl3>123</SubEl3>     
<SubEl4>456</SubEl4>         
</Node> 
<Node>     
<SubEl1>abc</SubEl1>     
<SubEl2>fgi</SubEl2>     
<SubEl3>124</SubEl3>     
<SubEl4>579</SubEl4>         
</Node> 
<Node>     
<SubEl1>ghi</SubEl1>     
<SubEl2>klm</SubEl2>     
<SubEl3>789</SubEl3>     
<SubEl4>012</SubEl4>         
</Node> 
</Root> 

Open in new window


I need to retrieve all the Node elements where SubEl1 has a value of "abc". Actually what I really need is a list of SubEl2 values for those Node elements.

I am having trouble writing XPath expression. Here is what I got so far:

XmlNodeList myList = xdoc.SelectNodes("Root/Node/SubEl1[text()='abc']");

Open in new window


but the above only give me a list of SubEl1, i.e. "abc", "abc",. while what I need is SubEl2, i.e. "def", "fgi"
ASKER CERTIFIED SOLUTION
Avatar of Gertone (Geert Bormans)
Gertone (Geert Bormans)
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You almost have it. Your expression should be...

Root/Node/SubEl1[text()='abc']/../SubEl2

Open in new window

Michaels solution will work but is highly inefficient.
Why go down and back up if you don't need to?

Also (I should have made that comment earlier) it is never a good idea to test explicitely for a text() node. XPath can split a text content in multiple text() nodes, and then this would not work
I you want to drill down to the text level, you should do
SubEl1[.='abc']
or even better
SubEl1[normalize-space(.) ='abc']
You can't delete a question that provided you with a good solution