You can call Nokogiri :: XML :: Node # ancestors.size for how deep the node is. But is there a way to determine how deeply nested the most deeply nested child of a node is?
Using
count(ancestor::node())
This expression expresses the number of ancesstors that the (current) node context in the document hierarchy has.
To find the nesting level of the “deepest nested child”, first you need to determine all the “leaf” nodes:
descendant-or-self::node()[not(node())]
and for each of them get their own level of nesting using the aforementioned XPath expression.
Then the maximum level of nesting (the maximum of all numbers produced) must be calculated, and this last calculation is not possible with pure XPath 1.0 .
This can be expressed in one XPath 2.0 expression:
max(for $leaf in /descendant-or-self::node()[not(node())], $depth in count($leaf/ancestor::node()) return $depth )
source share