Search code examples
xpath

How to select all nth descendants of a node using xpath?


I have a tree like this.

<div class="root">
    <div>
        <div>
            <div></div> <--- select this
        </div>
    </div>
    <div>
        <div>
            <div></div> <--- and select this
        </div>
    </div>
</div>

I tried the xpath //*[contains(@class, 'root')]/descendant::*[3] but it only selects the first one. How do I write an xpath that selects all nth descendants without having to do */*/*/*...?


Solution

  • If you want all the elements whose depth is three levels below the context item, you want ./*/*/*. If "three" here is a variable rather than a known constant then it becomes more difficult - and almost impossible in XPath 1.0 (which is what people usually want if they don't specify an XPath version).

    In XPath 2.0+ you could write $x/descendant::*[ancestor::*[$level] is $x]