2014-12-06 80 views
1

我有一個會是這樣如何使用XML ::的libxml解析XML文檔並構建一個Perl哈希

<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哈希XML數據。每個Bag元素的Identifier屬性應該是主散列鍵。

'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

你有問題嗎? – Borodin 2014-12-06 06:31:38

+0

是的,我無法讀取值並創建相同的散列結構 – Developer 2014-12-06 06:32:41

回答

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