如何使用 XML::LibXML 解析 XML 文档并构建 Perl 哈希 [英] How to use XML::LibXML to parse an XML document and build a Perl hash

查看:61
本文介绍了如何使用 XML::LibXML 解析 XML 文档并构建 Perl 哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的 XML 数据

I have XML data that will be like this

<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 哈希,如下所示.每个 Bag 元素的 Identifier 属性应该是主哈希键.

I want to parse this and create a Perl hash as below. The Identifier attribute of each Bag element should be the primary hash key.

'2' => {
  'Amount' => "21",
  'Code' => "XA",
  'Currency' => "INR",
}
'1' => {
  'Amount' => "0",
  'Code' => "XA",
  'Currency' => "INR",
}

这是我的 Perl 代码

This is my Perl code

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

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

How can I create the hash that I have described?

推荐答案

这个程序按你的要求做.它从 DATA 文件句柄读取样本数据的副本,并使用 Data::Dump 显示结果数据结构.

This program does as you ask. It reads a copy of your sample data from the DATA file handle, and uses Data::Dump to display the resultant data structure.

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

这篇关于如何使用 XML::LibXML 解析 XML 文档并构建 Perl 哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆