我有XML数据,就像这样
<Root>
<Bag Identifier="1">
<Code Amount="0" Code="XA" Conversion="0" Currency="INR" Desc="" Id="1"/>
</Bag>
<Bag Identifier="2">
<Code Amount="21" Code="XA" Conversion="0" Currency="INR" Desc="" Id="2"/>
</Bag>
</Root>
我想解析这个并创建一个Perl哈希,如下所示。每个Identifier
元素的Bag
属性应该是主哈希键。
'2' => {
'Amount' => "21",
'Code' => "XA",
'Currency' => "INR",
}
'1' => {
'Amount' => "0",
'Code' => "XA",
'Currency' => "INR",
}
这是我的Perl代码
my $parser = XML::LibXML->new();
my $xml_doc = $parser->parse_string($response);
my $test_node = $xml_doc->findnodes('//Bag/');
print Dumper($test_node);
print $test_node->find('@Id')->string_value();
如何创建我所描述的哈希?
答案 0 :(得分:4)
这个程序就像你问的那样。它从DATA
文件句柄中读取样本数据的副本,并使用Data::Dump
显示结果数据结构。
use strict;
use warnings;
use XML::LibXML;
my $data = XML::LibXML->load_xml(IO => \*DATA);
my %data;
my @bags = $data->findnodes('/Root/Bag');
for my $bag (@bags) {
my $id = $bag->getAttribute('Identifier');
my ($code) = $bag->getChildrenByTagName('Code');
my %item;
for my $attr (qw/ Amount Code Currency /) {
$item{$attr} = $code->getAttribute($attr);
}
$data{$id} = \%item;
}
use Data::Dump;
dd \%data;
__DATA__
<Root>
<Bag Identifier="1">
<Code Amount="0" Code="XA" Conversion="0" Currency="INR" Desc="" Id="1"/>
</Bag>
<Bag Identifier="2">
<Code Amount="21" Code="XA" Conversion="0" Currency="INR" Desc="" Id="2"/>
</Bag>
</Root>
<强>输出强>
{
1 => { Amount => 0, Code => "XA", Currency => "INR" },
2 => { Amount => 21, Code => "XA", Currency => "INR" },
}