【问题标题】:XML::Simple and unique namesXML::简单而独特的名称
【发布时间】:2012-02-21 18:49:00
【问题描述】:

我很难编写 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 成为一个数组,并且惨遭失败。

【问题讨论】:

  • 到底是什么问题?您有 $data-&gt;{Report}{ReportHost}{UNIQUE_1}$data-&gt;{Report}{ReportHost}{UNIQUE_2} 等。如果您需要遍历主机名,keys
  • HostProperties 的结束标签在哪里? XML 似乎不正确。

标签: perl xml-parsing xml-simple


【解决方案1】:

你说你在让 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 :-)

【讨论】:

  • 这非常有效。我尝试了这些选项,但从未一起尝试过。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
  • 1970-01-01
  • 1970-01-01
  • 2011-11-04
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多