YZlat
asked on
Need help with XPath
I have an xml file with the following content
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:
but the above only give me a list of SubEl1, i.e. "abc", "abc",. while what I need is SubEl2, i.e. "def", "fgi"
<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>
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']");
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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']
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
Open in new window