我想使用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;
}
}
}
}
答案 0 :(得分:1)
您的代码存在一些问题,其中一些问题归因于XML :: Simple:
$host->audit
,你需要$host->{audit}
(与host
相同)$data
了吗?创建的不是你期望的,顶级(scanJob
)不是由XML :: Simple创建的,有些级别被转换为哈希,而不是数组,因为你没有使用超级重要的ForceArray
选项,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解决方案很快会在这个帖子中弹出; - )