寻址嵌套在数组中的Perl哈希值

时间:2015-04-11 20:16:50

标签: arrays parsing hash key

您好我正在尝试将XML解析为嵌套的数组/哈希列表,并且我正在拼命地尝试从Contact属性获取一个键列表,这些键仍然是底层的hastable。这是我的代码:



my $xml = <<'EOD' ;
<root>
<instance>
        <contact>
                <customerfid>101</customerfid>
                <firstname>Steve</firstname>
                <lastname>Jobs</lastname>
        </contact>
        <contact>
                <customerfid>102</customerfid>
                <firstname>mark</firstname>
                <lastname>blue</lastname>
        </contact>
</instance>
<instance>
        <contact>
                <customerfid>444</customerfid>
                <firstname>john</firstname>
                <lastname>Doe</lastname>
        </contact>
</instance>
</root>
EOD

my $data = XMLin( $xml, forcearray => ['instance', 'customer', 'contact']) ;
print Dumper( $data ) ;

foreach $n (@{$data->{'instance'}}){
foreach $m (@{$data->{$n}{'contact'}}){
foreach $key (keys %{$data->{$m}}){
print "key: $key \n";
}
}
}
&#13;
&#13;
&#13;

当我运行dumper时,这是我的结构:

$VAR1 = {
      'instance' => [
                    {
                      'contact' => [
                                   {
                                     'firstname' => 'Steve',
                                     'customerfid' => '101',
                                     'lastname' => 'Jobs'
                                   },
                                   {
                                     'firstname' => 'mark',
                                     'customerfid' => '102',
                                     'lastname' => 'blue'
                                   }
                                 ]
                    },
                    {
                      'contact' => [
                                   {
                                     'firstname' => 'john',
                                     'customerfid' => '444',
                                     'lastname' => 'Doe'
                                   }
                                 ]
                    }
                  ]
    };

我做错了什么?

请帮帮我。

提前谢谢你,

1 个答案:

答案 0 :(得分:0)

您的XML有两个实例,这就是为什么要像这样创建数组的原因。将XML更改为以下内容:

<root> 
  <instance>
     <contact>
             <customerfid>101</customerfid>
             <firstname>Steve</firstname>
             <lastname>Jobs</lastname>
     </contact>
     <contact>
             <customerfid>102</customerfid>
             <firstname>mark</firstname>
             <lastname>blue</lastname>
     </contact>
     <contact>
             <customerfid>444</customerfid>
             <firstname>john</firstname>
             <lastname>Doe</lastname>
     </contact> 
  </instance> 
</root>