Search code examples
xpath-1.0

How to select a certain number of descendants of a node using xpath?


say i had the following xml:

<a>
   <b>
      <c>
         <d />
         <e />
      </c>
   </b>
   <g>
      <b>
         <h />
         <f />
      </b>
   </g>

if i want to select all the descendants of the node 'b' i can use the following xpath query:

//b//*

or using axes :

//b/descendant::*

But i want to select only 4 descendants of the node 'b', does anyone know how to do it please?

PS : i'm using xpath 1.0


Solution

  • It's settled! I just should use the parentheses like this :

    (//b/descendant::*)[position()<=4]
    

    because without them, the [position() <= 4] part will be applied to the descendant element's position in its parent rather than its position in the result node set.