We help IT Professionals succeed at work.

Need help with XPath

YZlat
YZlat asked
on
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"
Comment
Watch Question

Information Architect
CERTIFIED EXPERT
Top Expert 2006
Commented:
XmlNodeList myList = xdoc.SelectNodes("Root/Node[SubEl1='abc']/SubEl2");
Top Expert 2012

Commented:
You almost have it. Your expression should be...

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

Open in new window

Gertone (Geert Bormans)Information Architect
CERTIFIED EXPERT
Top Expert 2006

Commented:
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']
Gertone (Geert Bormans)Information Architect
CERTIFIED EXPERT
Top Expert 2006

Commented:
You can't delete a question that provided you with a good solution

Explore More ContentExplore courses, solutions, and other research materials related to this topic.