Loop through XML::Simple structure

David picture David · Jun 2, 2012 · Viewed 8.5k times · Source

So I have some xml file like this:

<?xml version="1.0" encoding="ISO-8859-1"?>
<root result="0" >
    <settings user="anonymous" >
            <s n="blabla1" >
                    <v>true</v>
            </s>
            <s n="blabla2" >
                    <v>false</v>
            </s>
            <s n="blabla3" >
                    <v>true</v>
            </s>
    </settings>
</root>

I want to go through all the settings using the XML Simple.

Here's what I have when I print the output with Data::Dumper:

$VAR1 = {
      'settings' => {
                      'user' => 'anonymous',
                      's' => [
                               {
                                 'n' => 'blabla1',
                                 'v' => 'true'
                               },
                               {
                                 'n' => 'blabla2',
                                 'v' => 'false'
                               },
                               {
                                 'n' => 'blabla3',
                                 'v' => 'true'
                               }
                             ]
                    },
      'result' => '0'
    };

And here's my code

 $xml = new XML::Simple;
 $data = $xml->XMLin($file);
 foreach $s (keys %{ $data->{'settings'}->{'s'} }) {
  print "TEST: $s $data->{'settings'}->{'s'}->[$s]->{'n'} $data->{'settings'}->{'s'}->[$s]->{'v'}<br>\n";
 }

And it returns these 2 lines, without looping:

TEST: n blabla1 true
TEST: v blabla1 true

I also tried to do something like this:

foreach $s (keys @{ $data->{'settings'}->{'s'} }) {

Without any success:

Type of arg 1 to keys must be hash (not array dereference) 

I can print:

$data->{'settings'}->{'s'}->[1]->{'n'} $data->{'settings'}->{'s'}->[1]->{'v'}

For each setting, but I can't loop through them.

How can I procede? What am I doing wrong?

Thanks a lot!

Answer

choroba picture choroba · Jun 2, 2012

Notice the square brackets in the dump: there is an array involved.

for (@{ $data->{settings}{s} }) {
    print $_->{n}, ' ', $_->{v}, "\n";
}

If you don't want to hardcode the n and v, just run keys on the dereferenced hash reference:

for my $s (@{ $data->{settings}{s} }) {
    print join(', ', map "$_ = $s->{$_}", keys %$s), "\n";
}