#!/bin/perl -w use strict; use XML::Twig; my $twig= new XML::Twig( twig_handlers => { _all_ => \&Piece_handler , # Call for each 'Program' elemetn } ); $twig->parsefile( shift @ARGV ); # build the twig #------------------------------------------------- sub Piece_handler{ my( $twig, $p)= @_; # handlers params are always # the twig and the element return unless $p->text && $p->text=~/design/; print $p->tag , ":",$p->text,"\n"; #Traverse and print ancestor tags for (my $ancestor = $p->parent; defined $ancestor; $ancestor=$ancestor->parent()){ print "\tParent : ", $ancestor->tag, "\n"; } $p->cut; # This one is processed, delete from tree .. } #### $ perl xmlt.pl xmldata2.xml para:This is a design XZY document for Project Parent : root $ perl xmlt.pl xmldata.xml header: This is a design XZY document for Project Parent : sect Parent : part Parent : root