in reply to Re^4: how to display descendants in XML with Perl's XML::Twig
in thread how to display descendants in XML with Perl's XML::Twig
poj#!perl use strict; use XML::Twig::XPath; my %record = (); my $twig= new XML::Twig::XPath( twig_handlers => { qr/^Line[1-5]|Author|Publisher|Book|Snap/ => \&line, qr/^C\d+/ => \& rating, }, ); $twig->parsefile( 'book.xml' ); sub line { my ($t,$e) = @_; $record{$e->name} = $e->text; if ($e->name eq 'Publisher'){ report(\%record); %record=(); } } sub rating { my ($t,$e) = @_; my $parent = $e->name.'.'; for ($e->descendants){ if ($_->name =~ /[XY]/){ push @{$record{$parent.$_->name}},$_->text; } } } sub report { my $hr = shift; my @f = qw(Book Snap Line1 Line2 Line3 Line4 Line5); my $line = join '|',@$hr{@f}; for my $key (sort keys %$hr){ if ($key =~ /^C\d+/){ print join '|',$line,$key,@{$hr->{$key}}; print "\n"; } } }
|
|---|