Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re^2: Extracting XML data from a tree

by Jenda (Abbot)
on Jun 05, 2013 at 08:30 UTC ( #1037170=note: print w/replies, xml ) Need Help??

in reply to Re: Extracting XML data from a tree
in thread Extracting XML data from a tree

See Simpler than XML::Simple.

Your code would break if there were multiple <Time> tag in one <Times>. Here's one of the ways to do this with XML::Rules. It handles the multiple <Time> tags and stops processing the XML once it finds the requested day.

use strict; use XML::Rules; use Data::Dumper; my $parser = XML::Rules->new( strispaces => 7, rules => { Time => 'as array', Times => 'pass', 'Day' => sub { my ($tag_name, $attrs, $context, $parent_data, $parser) = +@_; if ($attrs->{'day-of-week'} eq $parser->{parameters}) { $parser->return_this(join(', ', grep( defined($_), map + $_->{'start-time'}, @{$attrs->{Time}}))); } }, Month => sub{} } ); my $time = $parser->parse(\*DATA, 'MondayX'); print "Time: $time\n"; __DATA__ <?xml version="1.0" encoding="utf-8"?> <Month> <Week>

Enoch was right!
Enjoy the last years of Rome.

Replies are listed 'Best First'.
Re^3: Extracting XML data from a tree
by hdb (Prior) on Jun 05, 2013 at 08:51 UTC

    Agreed. The story does not look as favorable for XML::Simple anymore if the structure changes. If one makes it more robust using ForceArray => 1, then at least one more loop is required:

    my $xml = XMLin( 'CC.xml', ( ForceArray => 1 ) ); for my $day (@{ $xml->{Week}[0]{Day} }) { next unless $day->{'day-of-week'} eq "Tuesday"; for my $time ( @{ $day->{Times}[0]{Time} } ) { print $time->{'start-time'},"\n" if exists $time->{'start-time'}; } }

    Not really so "simple" anymore...

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1037170]
[Lady_Aleena]: Sanity check please? push @line, ref($list_addition ) eq 'ARRAY' ? @$list_addition : $list_addiction; # so I don't have the change existing uses of the sub.
[shmem]: $list_addiction should be $list_addition
Discipulus loose the tozzetto party!
[shmem]: .oO( addition of cookies for addiction to cookies )
[Lady_Aleena]: Other than my typos shmem. 8)
[shmem]: otherwise fine
[Discipulus]: tozzetti & vinsanto
[Lady_Aleena]: The whole line is push @line, ref($list_addition ) ? @$list_addition : $list_addition if $list_addition;
[Lady_Aleena]: And I forgot to do the array check, I'm such a doofus today.
[Lady_Aleena]: push @line, ref($list_addition ) eq 'ARRAY' ? @$list_addition : $list_addition if $list_addition; #trying again

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (9)
As of 2017-04-27 11:44 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (503 votes). Check out past polls.