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

I'm having trouble with this because the elements i'm pulling from have multiple attributes with the same name. So in the example below, I want to pull the last_child, but only where the Phone "name" attribute is "cell".
<Person name="Brian"> <Phones> <Phone name="cell" number="5551112233" /> <Phone name="cell" number="5557778899" /> <Phone name="home" number="5554441122" /> </Phones> </Person>

Replies are listed 'Best First'.
Re: Need XMLTwig help
by poj (Abbot) on Aug 22, 2013 at 20:36 UTC
    my $t = XML::Twig->new( twig_handlers => { 'Phones'=> \&phones } ); $t->parse($xml); sub phones { my ($t,$elt) = @_; print $elt->parent->att('name');; print ' Phone = ',$t->last_elt('Phone[@name="cell"]') ->att('number'),"\n"; print "\n"; }
    poj

      Being not the XPath expert, poj's post (++) animated to reduce my solution to the following:

      #!/usr/bin/env perl use 5.010; use strict; use warnings; use Data::Dumper; use local::lib 'lib'; use XML::Twig; my $string = <<EOF; <Person name="Brian"> <Phones> <Phone name="cell" number="5551112233" /> <Phone name="cell" number="5557778899" /> <Phone name="home" number="5554441122" /> </Phones> </Person> EOF my $twig = XML::Twig->new; $twig->parse($string); my @nodes = $twig->findnodes('/Person/Phones/Phone[@name="cell"]'); my @cellphones_nrs = map { $_->att('number') } @nodes; say "Cellphone: $cellphones_nrs[-1]" if @cellphones_nrs;

      McA

      Thank you! This helped a ton.
Re: Need XMLTwig help
by McA (Priest) on Aug 22, 2013 at 20:07 UTC

    Probably something like that:

    #!/usr/bin/env perl use 5.010; use strict; use warnings; use Data::Dumper; use local::lib 'lib'; use XML::Twig; my $string = <<EOF; <Person name="Brian"> <Phones> <Phone name="cell" number="5551112233" /> <Phone name="cell" number="5557778899" /> <Phone name="home" number="5554441122" /> </Phones> </Person> EOF my $twig = XML::Twig->new; $twig->parse($string); my @nodes = $twig->findnodes('/Person/Phones/Phone'); my @cellphones_nrs = map { $_->att('number') } grep { defined $_->att('name') && $_->att('name') eq 'cell' && defined $_->att('number') } @nodes; say "Cellphone: $cellphones_nrs[-1]" if @cellphones_nrs;

    Best regards
    McA

Re: Need XMLTwig help
by Anonymous Monk on Aug 23, 2013 at 06:59 UTC

    I'm having trouble

    So where is the code you're having trouble with?