使用perl XML :: Simple访问多级xml

时间:2014-08-20 16:07:12

标签: xml perl multi-level

所有,我已阅读了其他许多帖子,但未能完全理解这一点。我从Web服务中提取数据,并返回以下XML:

$VAR1 = {
    'error'           => 'EndOfResults',
    'model-responses' => {
        'model' => [
            {   
                'attribute' => {
                    'content' => 'wltvbswfc02',
                    'id'      => '0x1006e'
                },
                'mh' => '0x100540'
            },
            {   
                'attribute' => {
                    'content' => 'wltvsutm1ds02',
                    'id'      => '0x1006e'
                },
                'mh' => '0x100c80'
            },
            {   
                'attribute' => {
                    'content' => 'wltvsdora03',
                    'id'      => '0x1006e'
                },
                'mh' => '0x100c49'
            },
            ]

    },
    'throttle'     => '86',
    'total-models' => '86',
    'xmlns'        => 'http://www.ca.com/spectrum/restful/schema/response'
};

我需要退出' mh'和'内容'并指定一个哈希,内容为key,mh为value。我没有能够很好地获得数据结构..我感谢任何帮助。 谢谢! 罗伯特

1 个答案:

答案 0 :(得分:0)

您已将XML转换为perl数据结构,因此

use 5.010;
use warnings;
use Data::Dumper;

my $href = {
    "error"           => "EndOfResults",
    "model-responses" => {
        model => [
            {   attribute => { content => "wltvbswfc02", id => "0x1006e" },
                mh        => "0x100540",
            },
            {   attribute => { content => "wltvsutm1ds02", id => "0x1006e" },
                mh        => "0x100c80",
            },
            {   attribute => { content => "wltvsdora03", id => "0x1006e" },
                mh        => "0x100c49",
            },
        ],
    },
    "throttle"     => 86,
    "total-models" => 86,
    "xmlns"        => "http://www.ca.com/spectrum/restful/schema/response",
};

my %res = map { $_->{attribute}{content} => $_->{mh} }
    @{ $href->{"model-responses"}{model} };

say Dumper \%res;

以上版画:

$VAR1 = {
          'wltvsutm1ds02' => '0x100c80',
          'wltvsdora03' => '0x100c49',
          'wltvbswfc02' => '0x100540'
        };