Reputation: 1583
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.
Upvotes: 0
Views: 481
Reputation: 386386
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('*');
}
Upvotes: 6