Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have the xml below and I am trying to parse it
<?xml version="1.0" encoding="iso-8859-1"?> <xml> <offer id="60046"> <state>CO</state> <zip>80236</zip> <transit>1</transit> <phone_public>1</phone_public> <smoking></smoking> </offer> <offer id="6"> <state>MI</state> <zip>48120</zip> <transit>1</transit> <phone_public>1</phone_public> <smoking></smoking> </offer> <offer id="7"> <state>MI</state> <zip>43240</zip> <transit>1</transit> <phone_public>1</phone_public> <smoking></smoking> </offer>
here is my perlcode
use XML::Simple; my $content = get(xml.file); my $response = XMLin($content);

What I need is a line of code that will let me do a print $response->{'offer'}->{zip} and it give me 3 zip codes for the 3 zip codes in an xml file. I would really like it to be in a while loop.
Please help me, I am working on a project for victims of katrina.

Replies are listed 'Best First'.
Re: XML::Simple help -- please
by saintmike (Vicar) on Sep 06, 2005 at 01:31 UTC
    If you have a data structure and don't know what's in there, use Data::Dumper to dump it:
    use Data::Dumper; my $content = join '', <DATA>; my $response = XMLin($content); print Dumper($response);
    This will print something like
    $VAR1 = { 'offer' => { '6' => { 'zip' => '48120', 'transit' => '1', 'smoking' => {}, 'phone_public' => '1', 'state' => 'MI' }, '60046' => { 'zip' => '80236', 'transit' => '1', 'smoking' => {}, 'phone_public' => '1', 'state' => 'CO' }, '7' => { 'zip' => '43240', 'transit' => '1', 'smoking' => {}, 'phone_public' => '1', 'state' => 'MI' } } };
    and shows that starting from $response (which is a reference to a hash), you need to step down to the value of the offer key.

    There, you'll find another reference to a hash. This one contains one entry per id, so all you need to do is loop over these keys and then step down to the zip element of the sub-hash:

    my $response = XMLin($content); for my $id (keys %{$response->{offer}}) { print $response->{offer}->{$id}->{zip}, "\n"; }
    This will print the zip codes you're interested in:
    48120 80236 43240
Re: XML::Simple help -- please
by pg (Canon) on Sep 06, 2005 at 03:35 UTC

    In addition, there is no need for you to go through the extra step to get the content of the file. XMLin can directly accpet a file name.

    use XML::Simple; my $response = XMLin("offers.xml");