use warnings; use strict; use XML::LibXML; my $dom = XML::LibXML->load_xml({ location => '11117492.xml' }); # Build the tree my (%nodes,%tree); for my $part ($dom->findnodes('/products/product')) { for my $categories ($part->findnodes('./categories/category')) { my $cat_name = $categories->findvalue("name"); my $cat_id = $categories->findvalue("category_id"); my $cat_parent_id = $categories->findvalue("parent_id"); $nodes{$cat_id}{id} = $cat_id; $nodes{$cat_id}{name} = $cat_name; if ( length $cat_parent_id ) { push @{$nodes{$cat_parent_id}{children}}, $nodes{$cat_id}; } else { $tree{$cat_id} = $nodes{$cat_id} } # root node } } use Data::Dump; dd \%tree; # Debug # Walk the tree to find leaves my @queue = values %tree; while ( @queue ) { my $elem = shift @queue; if ( $elem->{children} ) { push @queue, @{$elem->{children}}; } else { print $elem->{name}," (",$elem->{id},")\n"; } } #### { 443026 => { children => [ { children => [{ id => 445720, name => "Carrot" }], id => 443120, name => "Vegetables", }, ], id => 443026, name => "Food", }, } Carrot (445720)