Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: XML parsing

by Jenda (Abbot)
on Mar 25, 2013 at 09:45 UTC ( #1025264=note: print w/replies, xml ) Need Help??

in reply to XML parsing

use strict; use XML::Rules; my $parser = XML::Rules->new( stripspaces => 7, rules => { _default => sub { my ($tag,$attrs,$context) = @_; if (%$attrs) { my @tags = (@$context[1..$#$context], $tag); my $content = delete $attrs->{_content}; if (%$attrs) { foreach my $attr (keys %$attrs) { $tags[-1] .= " $attr=\"$attrs->{$attr}\""; } } if (defined $content) { print join('::',@tags),"::",$content,"\n"; } else { print join('::',@tags),"\n"; } } return; } } ); $parser->parse(\*DATA); __DATA__ <FinInstnCdtTrf> <GrpHdr> <MsgId>0000003714</MsgId> ...

The code installs and then runs an unnamed subroutine for each tag encountered in the file. The subroutine checks whether there is any text content or attributes, prepares a list containing all parent tags except the root plus the current tag, appends attributes (if any) and then prints this list joined by '::' and appends the text content (if any) and returns nothing. The $parser->parse() in this case gets the data from the filehandle DATA (reads the stuff after __DATA__ in the script, but it can accept the XML in a scalar or from a file. Check the docs.

Enoch was right!
Enjoy the last years of Rome.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1025264]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2018-01-22 09:35 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (233 votes). Check out past polls.