XPath: Select parent nodes which have a subnode with an attribute
15,868
Solution 1
Remove the /
before SystemCompatibility
/Database/Package[SystemCompatibility/System[@mtm='2055']]
Solution 2
Try using:
/Database/Package/descendant::System[@mtm='2055']
Using the descendant:: operator will allow you to get any System grandchild of Package. http://www.w3schools.com/xpath/xpath_axes.asp
![kennyzx](https://i.stack.imgur.com/8mNbc.png?s=256&g=1)
Author by
kennyzx
Gentlemen, it has been a privilege debugging with you tonight. mailto://[email protected] Half the pleasure of coding comes from a good (I mean, really good) keyboard and an ultra-wide monitor.
Updated on July 19, 2022Comments
-
kennyzx almost 2 years
I want to get the "Package" nodes which have a "System" grandchild with an "mtm" attribute, and the value of the "mtm" attribute is "2055". For the below example document, only the first Package node should be returned.
I use
"/Database/Package[/SystemCompatibility/System[@mtm='2055']]"
but it does not work. What is wrong with this expression?
<?xml version="1.0" encoding="UTF-8"?> <Database version="300"> <Package id="6imb05ww" description="ThinkPad Modem Adapter"> <SystemCompatibility> <System mtm="8742" os="Windows XP" oslang="en" /> <System mtm="2055" os="Windows XP" oslang="jp" /> </SystemCompatibility> </Package> <Package id="6imb06ww" description="ThinkPad Modem Adapter"> <SystemCompatibility> <System mtm="3046" os="Windows XP" oslang="en" /> </SystemCompatibility> </Package> </Database>
-
John Giotta over 12 yearsThis will return only the System node and not the entire Package node
-
kennyzx over 12 yearsIt works, thanks. My bad, i thought i have tried this approach but actually i didn't.
-
cookie_monster over 12 yearsAh, you're right. I misunderstood the question. Thanks for pointing that out.
-
John Giotta over 12 yearsThis would work with some modification! Note the encapsulating brackets
/Database/Package[descendant::System[@mtm='2055']]
-
cookie_monster over 12 yearsI was just testing that exact code out to make sure it would work, but you beat me to getting it posted. Thanks for posting the correction too!