[Canberra-pm] Parsing an XML document using XML::Twig and using it on an Template
Mark Suter
suter at zwitterion.org
Thu Mar 18 00:58:03 PDT 2010
John,
> I am trying to read an XML document into a hash handler that can be
> used on the Template package. I thought that XML::Twig would be good
> for this but I have no idea how to create a hash/array "thingy" that
> can be passed to the Template module. Can someone help with this? I
> don't understand the hash/array structure created by the XML::Twig and
> for the input to the Template.
The code below works for me. I've run this email using perl -x
and it produces this output:
Dumper:
$VAR1 = {'thing' => [{'name' => 'Perl','rating' => 'Awesome'},{'name' => 'Python','rating' => 'Awesome'}]};
Template:
Perl is Awesome.
Python is Awesome.
I wouldn't recommend this coding style normally and it lacks a
lot of the normal error checking; however, it looks cool ;)
--
Mark Suter http://zwitterion.org/ | I have often regretted my
<mark.suter at member.sage-au.org.au> | speech, never my silence.
mobile 0411 262 316 - gpg 2C71D63D | Xenocrates (396-314 B.C.)
----------------------------- perl -x -----------------------------
#!/usr/bin/perl
# [MJS 18 Mar 2010] XML::Twig -> Template demo
use strict;
use warnings;
use XML::Twig;
use Template;
use Data::Dumper;
## Contrived sample XML ;)
my $xml = <<'EOF' ;
<?xml version="1.0" ?>
<ratings>
<thing><name>Perl</name><rating>Awesome</rating></thing>
<thing><name>Python</name><rating>Awesome</rating></thing>
</ratings>
EOF
## Contrived sample template ;)
my $template = <<'EOF' ;
Dumper:
[% dump %]
Template:
[% FOREACH thing IN thing -%]
[% thing.name %] is [% thing.rating %].
[% END -%]
EOF
## Parse the XML into a simple data structure
my $data = XML::Twig->parse($xml)->simplify();
## Add a text dump of that structure to itself
$data->{dump} = Data::Dumper->new( [$data] )->Indent(0)->Dump();
## Template it
Template->new()->process( \$template, $data );
__END__
More information about the Canberra-pm
mailing list