For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > July 2005 > xml::simple









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author xml::simple
info@perlromania.net

2005-07-25, 9:24 am


Hello,

I've just made a simple script using xml::simple,
and I am stuck on something:

I have an xml file that looks like this:

<person>
<address>
<str>Somewhere</str>
<nr>18</nr>
<sc>a</sc>
</address>
</person>
<person>
<address>
<str>Somewhere else</str>
<nr>3</nr>
<sc>a</sc>
<zone>bc</zone>
</address>
</person>
.....

So my question would be, how can I handle dynamic <address> fields
(ex. the above code) and be able to refer to each key/value pair
inside <address> ?

Thanks !

Xavier Noria

2005-07-25, 9:24 am

On Jul 25, 2005, at 11:15, info@perlromania.net wrote:

>
> Hello,
>
> I've just made a simple script using xml::simple,
> and I am stuck on something:
>
> I have an xml file that looks like this:
>
> <person>
> <address>
> <str>Somewhere</str>
> <nr>18</nr>
> <sc>a</sc>
> </address>
> </person>
> <person>
> <address>
> <str>Somewhere else</str>
> <nr>3</nr>
> <sc>a</sc>
> <zone>bc</zone>
> </address>
> </person>
> ....
>
> So my question would be, how can I handle dynamic <address> fields
> (ex. the above code) and be able to refer to each key/value pair
> inside <address> ?


XML::Simple is itself dynamic in that sense. Each address node
becomes a hashref with as many keys as fields it finds. You can then
use each() and friends to inspect them as you'd do with any hash. See
a dump of the structure below.

-- fxn

% cat foo.pl
use XML::Simple;
use Data::Dumper;

my $xml = XMLin(<<EOX);
<test>
<person>
<address>
<str>Somewhere</str>
<nr>18</nr>
<sc>a</sc>
</address>
</person>
<person>
<address>
<str>Somewhere else</str>
<nr>3</nr>
<sc>a</sc>
<zone>bc</zone>
</address>
</person>
</test>
EOX

print Dumper($xml);
% perl foo.pl
$VAR1 = {
'person' => [
{
'address' => {
'sc' => 'a',
'str' => 'Somewhere',
'nr' => '18'
}
},
{
'address' => {
'sc' => 'a',
'str' => 'Somewhere else',
'zone' => 'bc',
'nr' => '3'
}
}
]
};



Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com