for &{ sort :d :k count(ancestor::*) //mml:msub } ls . ; #### swift Found 1 node(s). poland swift a Found 1 node(s). China poland swift a Found 1 node(s). Canada police bangalore Found 1 node(s). #### #!/usr/bin/perl use warnings; use strict; use feature qw{ say }; use XML::LibXML; my $xml = 'XML::LibXML'->load_xml(location => '/path/to/file.xml'); say for map $_->[0], sort { $b->[1] <=> $a->[1] } map [ $_, $_->findvalue('count(ancestor::*)')], $xml->findnodes('//mml:msub');