Search code examples
xmlxpathdescendant

XPath: Select node based on depth of descendant node type


I need to return the string "A1" or the string "A2" dependent upon the maximum depth of the "B" nodes beneath their containing nodes:

<xmlDoc>
 <A>A1
  <B>
   <B>
    <B>
    </B>
   </B>
  </B>
  <B>
  </B>
</A>
<A>A2
 <B>
  <B>
  </B>
 </B>
  <B>
   <B>
   </B>
  </B>
 </A>
</xmlDoc>

The descendant axis does not seem appropriate to determine the "depth" of the B nodes (Ex: /xmlDoc/A[count(descendant::B)>2]). The "A" node containing the string "A1" has a maximum "B" node depth of 3 but seems to have 4 "descendant" "B" nodes...

How would one construct an XPath expression to return the string "A1" based upon the "3 deep" occurrence of the "B" nodes in the first "A" node?


Solution

  • Descendant counts all children of the node. If you want chain of B nodes, write it so

    /xmlDoc/A[B[B[B]]]