问题
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