我在Perl中有一个关于findnodes
的简单问题。假设我有以下示例XML
(test.xml
)文件作为输入
<SquishReport version="2.1" xmlns="http://www.froglogic.com/XML2">
<test name="mainTest1">
<test name="test1">
</test>
<test name="test2">
</test>
</test>
<test name="mainTest2">
<test name="test3">
</test>
<test name="test4">
</test>
</test>
</SquishReport>
然后在Perl中我想在列表中保存第一个测试名称,如下所示
use warnings;
use XML::LibXML;
my $file = 'test.xml';
my $xpc = XML::LibXML::XPathContext->new();
my $doc = XML::LibXML->load_xml(location => $file);
for my $entry ($xpc->findnodes('//SquishReport/test', $doc))
{
$testCases[$count] = $entry->getAttribute('name');
$count = $count + 1;
}
print @testCases;
print "\n";
但是我在运行上面的代码后得到了空列表。我发现我是否在根节点(SquishReport
)中删除了其余的解释,即
version =“2.1”xmlns =“http://www.froglogic.com/XML2”
然后每件事都没问题,然后我就有了所需的输出。但是,如果我在主根中包含上述解释,则不会。
有谁知道为什么会这样?谢谢!
答案 0 :(得分:3)
use warnings;
use XML::LibXML;
my $file = 'test.xml';
my $xpc = XML::LibXML::XPathContext->new();
$xpc->registerNs(fl => 'http://www.froglogic.com/XML2'); # <---
my $doc = XML::LibXML->load_xml(location => $file);
for my $entry ($xpc->findnodes('//fl:SquishReport/fl:test', $doc)) # <---
{
$testCases[$count] = $entry->getAttribute('name');
$count = $count + 1;
}
print @testCases;
print "\n";
清理:
use strict;
use warnings qw( all );
use XML::LibXML qw( );
use XML::LibXML::XPathContext qw( );
my $qfn = 'test.xml';
my $doc = XML::LibXML->load_xml( location => $qfn );
my $xpc = XML::LibXML::XPathContext->new();
$xpc->registerNs(fl => 'http://www.froglogic.com/XML2');
my @test_cases;
for my $entry ($xpc->findnodes('//fl:SquishReport/fl:test', $doc)) {
push @test_cases, $entry->getAttribute('name');
}
print "@testCases\n";