0

我很难制作 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 成为数组并且惨遭失败。

4

1 回答 1

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

我会建议使用不同的模块:-)

于 2012-01-29T20:26:12.053 回答