Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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.

Jenda
Enoch was right!
Enjoy the last years of Rome.


Comment on Re: XML parsing
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1025264]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2014-09-24 00:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (243 votes), past polls