accessing Multi level xml with perl XML::Simple

断了今生、忘了曾经 提交于 2019-12-13 18:23:26

问题


All, I have read manyother other posts and have not been able to quite get a handle on this. I am pulling data form a web service and i am returned the following 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'
};

I need to pull out 'mh' and 'content' and assign to a hash with content as key and mh as value. I have not been able to get data structure quite right.. I appreciate any help. Thanks! Robert


回答1:


You already converted the XML into perl data structure, so

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;

The above prints:

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


来源:https://stackoverflow.com/questions/25409509/accessing-multi-level-xml-with-perl-xmlsimple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!