Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath: how to search in all descendant nodes hierarchy by an attribute value?

Tags:

xml

xpath

consider following XML:

<parent no=1>
   <child id=10>
      <child id=101>
      </child>
      <child id=102>
         <child id=10201>
            I want this line.
         </child>
      </child>
   </child>
</parent>
<parent no=2>
   ...
</parent>

I want to get the value of the element child with id=10201 which is under parent no=1, not by specifying all the path. I mean I don't want to get the node this way:

parent[@no=1]/child[@id=10]/child[@id=102]/child[@id=10201]

instead, since I have ids per child I should be able to fetch the node, directly by one condition, something like this:

parent[@no=1]/*/child[@id=10201]

How can I do that?

like image 422
mostafa.S Avatar asked Nov 18 '25 21:11

mostafa.S


1 Answers

One way to do it

//child[@id = 10201 and ancestor::parent[@no = 1]]

and another, like you attempted

//parent[@no = 1]//child[@id = 10201]
like image 78
Tomalak Avatar answered Nov 21 '25 13:11

Tomalak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!