我很难让Perl脚本正确解析XML文件,如下所示:
<Report name="NAME">
<ReportHost name="UNIQUE_1"><HostProperties>
<tag name="TAG_1">tag_value</tag>
<tag name="TAG_2">tag_value</tag>
</ReportHost>
<ReportHost name="UNIQUE_2"><HostProperties>
<tag name="TAG_1">tag_value</tag>
<tag name="TAG_2">tag_value</tag>
</ReportHost>
现在,我需要以某种方式调用那些 UNIQUE_n ,但我无法管理。 Dumper返回如下结构:
'Report' => {
'ReportHost' => {
'UNIQUE_1' => {
'HostProperties' => {
'tag' => { [...]
我尝试过ForceArray,但是无法使ReportHost成为一个数组而且失败了。
答案 0 :(得分:3)
你说你在让Perl“正确解析”XML时遇到了麻烦但你没有说出你想要的结果。撇开你的示例XML缺少一些结束标记的事实,也许你想要这样的东西:
my $report = XMLin(\*DATA,
ForceArray => [ 'ReportHost', 'tag' ],
KeyAttr => { tag => 'name' },
ContentKey => '-content',
);
print Dumper($report);
给出了:
$VAR1 = {
'ReportHost' => [
{
'HostProperties' => {
'tag' => {
'TAG_1' => 'tag_value',
'TAG_2' => 'tag_value'
}
},
'name' => 'UNIQUE_1'
},
{
'HostProperties' => {
'tag' => {
'TAG_1' => 'tag_value',
'TAG_2' => 'tag_value'
}
},
'name' => 'UNIQUE_2'
}
],
'name' => 'NAME'
};
你可以像这样循环数据:
my $report_hosts = $report->{ReportHost};
foreach my $report_host ( @$report_hosts ) {
print "Report: $report_host->{name}\n";
my $props = $report_host->{HostProperties}->{tag};
print " TAG_1: $props->{TAG_1}\n";
print " TAG_2: $props->{TAG_2}\n";
}
我建议using a different module但是: - )