循环遍历XML :: Simple结构

时间:2012-06-02 10:38:48

标签: perl xml-parsing xml-simple

所以我有一些像这样的xml文件:

<?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>

我想使用XML Simple进行所有设置。

这是我用Data :: Dumper打印输出时的内容:

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

这是我的代码

 $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";
 }

它返回这两行,没有循环:

TEST: n blabla1 true
TEST: v blabla1 true

我也尝试过这样的事情:

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

没有任何成功:

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

我可以打印:

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

对于每个设置,但我无法遍历它们。

我该如何处理?我做错了什么?

非常感谢!

1 个答案:

答案 0 :(得分:5)

注意转储中的方括号:涉及到一个数组。

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

如果您不想对nv进行硬编码,只需在解除引用的哈希引用上运行keys

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