foreach my $file ( @filelist ) { my $twig= new XML::Twig(); $twig->parsefile($file); my $twig_root = $twig->root; foreach my $xpath_arg ( @xpath_args ) { my @xpath_result = $twig_root->get_xpath($xpath_arg); foreach ( @xpath_result ) { print &complete_path($_); $_->contains_only_text ? print ' : ' . $_->text . "\n" : print "\n"; } } } sub complete_path() { my( $elt )= @_; return '/' . join( '/', map { tag_desc($_) } reverse $elt->ancestors_or_self); } sub tag_desc { my( $elt )= @_; my %atts= %{$elt->atts}; my $atts= %atts ? '[' . join( " ", map { qq{$_="$atts{$_}"} } sort keys %atts) . ']' : ''; return $elt->tag . $atts; } Running : ./show_xpath_value.pl -x '//*[@keep="1"]' /doc/elt[att1="1" keep="1"] /doc/elt[att1="1" keep="1"]/elt2[att2="2" keep="1"] : foo /doc/elt[att1="1"]/elt2[att2="2" keep="1"] : bar2 /doc/elt[att1="1" keep="1"] /doc/elt[att1="1" keep="1"]/elt2[att2="2" keep="1"] : foo3 /doc/elt[att1="1" keep="1"]/elt2[att2="2" keep="1"] : bar3