如何使用XML :: LibXML来解析XML文档并构建Perl哈希

时间:2014-12-06 06:27:10

标签: perl

我有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();

如何创建我所描述的哈希?

1 个答案:

答案 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" },
}