my $t= parse XML::Twig::Elt(\*DATA); $t->sort_children( sub { my $elt = shift; my $top = $elt->att('attribute'); my $kid = sprintf '%04d', ($elt->first_child->tag =~ s/Child//r); return $top . $kid; }); $_->print for $t->children;