【问题标题】:The below code does not print output下面的代码不打印输出
【发布时间】:2014-01-15 10:35:46
【问题描述】:

我想使用 perl 解析 xml 文件,我想检索 Audit 标签的值,但没有产生输出。

use strict;
use warnings;
use XML::Simple;
use Data::Dumper;

my $xml = <<'__EOI__';
<scanJob>
   <hosts>
      <host>
        <audit>
           <rthID>31406</rthID>
           <cve>N/A</cve>
           <cce>N/A</cce>
           <iav>N/A</iav>
           <name>OpenSSH Memory Corruption Vulnerability - (20131108) - Banner</name>
           <description>OpenSSH 6.4 </description>
           <pciReason>Default</pciReason>
           <pciPassFail>Pass</pciPassFail>
           <cvssScore>N/A</cvssScore>
           <fixInformation>Upgrade OpenSSH 6.4 or later.</fixInformation>
           <exploit>No</exploit>
           <context>TCP:22</context>
        </audit>
     </host>
  </hosts>
</scanJob>
__EOI__

my $xs = new XML::Simple;

my $data = $xs->XMLin(\$xml);
for my $scanJob (@{$data->{scanJob} }) {
                for my $hosts (@{$scanJob->hosts }) {
                for my $host (@{$hosts->host }) {
                        for my $audit (@{$host->audit }) {
                                my $rthID   = $audit->{rthID};
                                print $rthID;
                        }
                }
        }
}

【问题讨论】:

  • 你能发布你试图解析的 XML 吗?
  • 31406N/AN/AN/AOpenSSH 内存损坏漏洞 - (20131108) - BannerOpenSSH 6.4 DefaultPassN/A升级 OpenSSH 6.4 或更高版本。NoTCP:22
  • 你不能编辑你的帖子吗?很难从评论中阅读它
  • 我无法正确编辑这个?只想说标签对齐如下 -> -> -> -> 表示 rthID 是审计的孩子,审计是主机的孩子,主机是主机的孩子, hosts 是 scanJob 的子节点
  • @mirod 你能看看吗?

标签: xml perl parsing


【解决方案1】:

您的代码有几个问题,其中一些是由于 XML::Simple:

  • XML::Simple 创建哈希,你不能说$host-&gt;audit,你需要$host-&gt;{audit}(和host一样)
  • 您是否使用 Data::Dumper 打印了$data?创建的不是您所期望的,顶级 (scanJob) 不是由 XML::Simple 创建的,某些级别被转换为哈希,而不是数组,因为您没有使用超级重要的@987654326 @ option, a;所以元素之一是 name 的事实在最低级别创建了一个哈希

坦率地说,如果你想提取rthID 的值,我的菜XML::Simple 并使用XML::LibXML、XML::Twig 或XML::XSH2,就不会那么头疼了:

use XML::Twig;
XML::Twig->new( twig_handlers => { rthID => sub { print $_->text, "\n"; } })
         ->parsefile( $file1);

use XML::LibXML;
my $data= XML::LibXML->load_xml(location => $file1);
foreach my $rthid (@{$data->findnodes( '//rthID')})
  { print $rthid->textContent, "\n"; }

我相信 XSH2 解决方案很快就会出现在这个帖子中;--)

【讨论】:

  • 其实我不想要审计子标签的 rthID 值,我想检索审计标签的 10 个子标签值。我现在只提供了 1 个,即 rthID
  • 好吧,我只能回答你问的问题......调整 XML::Twig 或 XML::LibXML 代码来做你想做的事情应该不会太难:对于 XML::Twig,在 audit 标签上设置一个处理程序,然后使用 children,对于 XML::LibXML,使用 XPath 选择 audit 元素,然后获取子元素
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-15
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-23
相关资源
最近更新 更多