Search code examples
xmlperlxpathlibxml2xml-libxml

How to count number of levels (depth) in XML branch in perl XML::LibXML?


I have a very simple problem. I want to find number of levels of an XML branch. Like:

<span>
 <span>
  <math xmlns="http://www.w3.org/1998/Math/MathML" display="inline">
    <msup>
     <mn>34</mn>
     <mi>o</mi>
    </msup>
  </math>
  <span> </span>
 </span>
</span>

Should give a depth count of 5 when computed from the very first (root) span tag. I am using XML::Libxml. Thanks.


Solution

  • use List::Util qw( max );
    
    sub max_depth {
       my ($ele) = @_;
       return 1 + max 0, map max_depth($_), $ele->findnodes('*');
    }
    

    The following accepts any kind of nodes instead of just element nodes (e.g. a document node):

    use List::Util  qw( max );
    use XML::LibXML qw( XML_ELEMENT_NODE );
    
    sub max_depth {
       my ($node) = @_;
       my $base = $node->nodeType == XML_ELEMENT_NODE ? 1 : 0;
       return $base + max 0, map max_depth($_), $node->findnodes('*');
    }