Gizmo has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to parse an XML file, if a Tag exists it should print the application "Name" attribute. From the XML snippet if "<Timeout>900</Timeout>" exists it should print Name="App1". Of course the Timeout value could be anything. So my thinking is to match the Tag for "Timeout" if found print 'App Name' and 'Timeout' Value. I'm trying to use the code below, but not sure how I can recurse through all the child/parent to match the Timeout Tag (The depth isn't always the same) and then print App Name.
use strict; use warnings; use XML::Twig; my $twig=XML::Twig->new( twig_handlers => { 'Hierarchy' => \&print_elt_text } ); $twig->parsefile( "a.xml"); sub print_elt_text { my( $t, $section)= @_; ? $t->purge; }
XML Snippet.
<Configuration> <Version>1.0</Version> <User>root</User> <Parameter ParameterName="Text">Enable</Parameter> <Parameter ParameterName="Text2">Disable</Parameter> <Hierarchy> <Application Name="App1"> <Properties> <Admin>root</Admin> <User>root</User> <Timeout>900</Timeout> </Properties> </Application> <Application Name="App2"> <Properties> <User>root</User> </Properties> </Application> </Hierarchy> </Configuration>

Replies are listed 'Best First'.
Re: XML::Twig Search
by ikegami (Patriarch) on May 17, 2010 at 19:11 UTC
    I'd use the following, but Twig's limited XPath support cannot handle it:
    use strict; use warnings; use XML::Twig qw( ); my $twig = XML::Twig->new( twig_roots => { 'Application[Properties/Timeout]' => sub { my ($t, $elt) = @_; print("$elt->{att}{Name}\n"); $t->purge; } }, ); $twig->parsefile('a.xml');

    This works:

    use strict; use warnings; use XML::Twig qw( ); my $twig = XML::Twig->new( twig_handlers => { 'Application/Properties/Timeout' => sub { my ($t, $elt) = @_; print($elt->parent->parent->att('Name'), "\n"); }, }, ); $twig->parsefile('a.xml');
      Thanks, I see it matches any Application/Properties/Timeout so if I have many levels it detects it, exactly what I was trying to do.
Re: XML::Twig Search
by toolic (Bishop) on May 17, 2010 at 19:03 UTC
    This sub works for your XML input:
    sub print_elt_text { my ($t, $section) = @_; my $appl = $section->first_child('Application'); my $timeo = $appl->first_child('Properties')->first_child('Timeout +'); if (defined $timeo) { print $appl->att('Name'), ' ', $timeo->text(), "\n"; } } __END__ App1 900