Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (4)
As of 2016-10-22 17:12 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (297 votes). Check out past polls.