我想使用该XML::DOM
模块解析一个简单的 XML 文档以进行散列。
<?xml version ="1.0"?>
<Select>
<book>
<prop Name = "prop1" Title = "title1" />
<prop Name = "prop2" Title = "title2" />
</book>
<fruit>
<prop Name = "prop3" Title = "title3" />
<prop Name = "prop4" Title = "title4" />
</fruit>
</Select>
并且预期的输出是-
$VAR1 = {
Select => {
book => {
prop => [
{ Name => "prop1", Title => "title1" },
{ Name => "prop2", Title => "title2" },
],
},
fruit => {
prop => [
{ Name => "prop3", Title => "title3" },
{ Name => "prop4", Title => "title4" },
],
},
},
}
我写的代码是:
use strict;
use XML::DOM;
use Data::Dumper;
my @stack;
my %hash;
push @stack,\%hash;
my $parser = new XML::DOM::Parser;
my $doc = $parser -> parsefile('demo.xml');
my $root = $doc->getDocumentElement();
my $rootnode = $root->getTagName;
################################################################
foreach my $node ($doc->getElementsByTagName($rootnode)){
push @stack,$stack[$#stack]->{$rootnode};
my @childnode = $node->getChildNodes();
foreach my $child(@childnode){
if($child->isElementNode){
my $childname = $child->getNodeName();
pop(@stack);
push @stack,$stack[$#stack]->{$rootnode} = {$childname,{}};
my @childnodes2 = $child->getChildNodes();
foreach my $subchild(@childnodes2){
if($subchild->isElementNode){
my $subchildname = $subchild->getNodeName();
my $name = $subchild->getAttributes->getNamedItem('Name')->getNodeValue;
my $title = $subchild->getAttributes->getNamedItem('Title')->getNodeValue;
pop(@stack);
push @stack,$stack[$#stack]->{$rootnode}->{$child->getNodeName()} = {$subchildname,{}}; #{} contains $name or $title
}
}
}
}
}
print Dumper(\%hash);
我认为,我无法正确推送和弹出数组。另外,我不想使用XML::Simple
和递归。
我怎样才能在 Perl 中做到这一点?