简体   繁体   中英

accessing Multi level xml with perl XML::Simple

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

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'
        };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM