Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of ancestors of a precise node

Tags:

xpath

As usual my question is simple but I dont seem to be able to do what I want :

<test targetAttribute="level 1">
   <test targetAttribute="level 2">
      <test targetAttribute="level 3">
         <test targetAttribute="level 4">
            <test targetAttribute="level 5">
            </test>
         </test>
      </test>
   </test>
</test>

I want to know how many ancestors have the //test/@targetAttribute="level 5" node.

I have been trying thousand things, nothing is working for me :

  • count(//test/@targetAttribute="level 5"/ancestor::*)
  • //test/@targetAttribute="level 5"/count(ancestor::*)
  • count(ancestor::*[//test/@targetAttribute="level 5"])
  • ...

I just don't seem to be able to find what I am looking at on google...

like image 355
Kermit Avatar asked Oct 26 '25 14:10

Kermit


1 Answers

The notion of ancestor is known for element, so, first, you need to find the target element which has @targetAttribute="level 5" :

//test[@targetAttribute='level 5']

From here, you should be able to modify the above XPath to return count of ancestor elements of the target element :

count(//test[@targetAttribute='level 5']/ancestor::*)

Demo

like image 118
har07 Avatar answered Oct 29 '25 18:10

har07



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!