将XML转换为Perl哈希



对于下面的XML结构,我正在尝试获得相应的Perl哈希数组

<root>
<ref name="abc_sia_%version1.ref%">
<func envname = "test01" objectdir = "/home/pv66" base="default_771"/>
</ref>
</root>

我可以使用将其转换为perl哈希

my $xml = new XML::Simple;
my $data = $xml->XMLin("/home/pv66", ForceArray => 1, KeyAttr => { ref => "name"});
print Dumper ($data);

散列原来是:

$VAR1 = {
'ref' => {
'abc_sia_%version1.ref' => {
'func' => [
{
'envname' => 'test01',
'objectdir' => '/home/pv66',
'base' => 'default_771'
}
]       
}
}
};

虽然我需要删除上面的引用,但基本上我希望散列看起来像:

$VAR1 = {
'abc_sia_%version1.ref' => {
'func' => [
{
'envname' => 'test01',
'objectdir' => '/home/pv66',
'base' => 'default_771'
}
]       
}
};

有什么方法可以转换哈希吗??

XML::LibXML的文档对于初学者来说可能有点简洁。我推荐Grant的教程。

XML::LibXML没有一个";根据该XML文档制作数据结构";方法正如XML::Simple所显示的那样,这种方法过于脆弱,无法发挥作用。相反,您可以自己遍历DOM,将您想要的任何数据提取到数据结构中。就我个人而言,我喜欢使用XPath表达式来确定我想要的内容。

#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use Data::Dumper;
use XML::LibXML;
# Here, I've loaded the XML from the DATA filehandle
# (at the end of the source file). Other options are
# available.
my $dom = XML::LibXML->load_xml(IO => *DATA);
my $data;
# Look for all '/root/ref' nodes...
for my $ref ($dom->findnodes('/root/ref')) {
# Get the name of the ref node
my $key = $ref->findvalue('./@name');
my @funcs;
# Look for all of the 'func' nodes below this ref node
for my $func ($ref->findnodes('./func')) {
my $func_data;
# For each attribute we're interested in...
for (qw[envname objectdir base]) {
# Get the value of the attribute
$func_data->{$_} = $func->findvalue("./@$_");
}
push @funcs, $func_data;
}
$data->{$key}{func} = @funcs;
}
say Dumper $data;
__DATA__
<root>
<ref name="abc_sia_%version1.ref%">
<func envname = "test01" objectdir = "/home/pv66" base="default_771"/>
</ref>
</root>

原来我所要做的就是添加另一个级别的搜索并将其分配给一个变量。无论如何,我都会发布解决方案:

my $xml = new XML::Simple;
my $data = $xml->XMLin("/home/pv66", ForceArray => 1, KeyAttr => { ref => "name"});
my data1 = $data->{'ref'};
print Dumper ($data1);

返回:


$VAR1 = {
'abc_sia_%version1.ref' => {
'func' => [
{
'envname' => 'test01',
'objectdir' => '/home/pv66',
'base' => 'default_771'
}
]       
}
};

这就是我想要的结构。

最新更新