如何访问在perl中同样是键、值对的散列值

k10s72fa  于 2023-02-16  发布在  Perl
关注(0)|答案(1)|浏览(161)

我有一个散列如下,我需要访问它,并把信息在xml中。我不能正确访问。我面临着理解和使用散列数据类型的困难。散列需要参考:

$VAR1 = {
          'state1' => {
                        'code' => '328',
                        'num' => '179237'
                      },
          'state2' => {
                        'code' => '987',
                        'num' => '0.8736'
                      },
          'state3' => {
                        'code' => '326',
                        'num' => '582048'
                      }
        };

我需要编写的xml格式是

<Root>

 <Info>
  <statename>state1</statename>
  <code>328<code>
  <num>179237<num>
  </Info>

 <Info>
  <statename>state2</statename>
  <code>987<code>
  <num>0.8736<num>
 </Info>

<Info>
  <statename>state3</statename>
  <code>326<code>
  <num>582048<num>
 </Info>
 
</Root>

我需要使用XML::LibXML库,抱歉没有从我的结束张贴尝试的代码。因为我需要它立即和我在访问哈希缓慢,我无法提供任何适当的工作代码。请帮助。:)

$size = keys %my_hash; 
for(my $i=0; $<=$size;$i++){
 my $tags = $doc->createElement('Info');
 my %tags = 
   statename => 
   code =>
   num => 
}

for my $state_name (sort keys %my_hash){
 my $state_tag = $doc->createElement ($statename);
 my $codetag->appendTextNode($code);
 $num = ->appendChild($statetag) 
}

还请指出任何文档,以了解从开始访问散列和使用在xml中。

q7solyqu

q7solyqu1#

#! /usr/bin/perl
use warnings;
use strict;

use XML::LibXML;

my %hash = ('state1' => {
                'code' => '328',
                'num' => '179237'
            },
            'state2' => {
                'code' => '987',
                'num' => '0.8736'
            },
            'state3' => {
                'code' => '326',
                'num' => '582048'
            });

my $dom = 'XML::LibXML::Document'->new('1.0', 'UTF-8');
$dom->setDocumentElement(my $root = $dom->createElement('root'));

for my $state (sort keys %hash) {
    my $info = $root->addNewChild("", 'Info');
    $info->addNewChild("", 'statename')->appendText($state);
    for my $key (qw( code num )) {
        $info->addNewChild("", $key)->appendText($hash{$state}{$key});
    }
    $info->appendText("\n");
}
print $dom;

相关问题