首页 > 解决方案 > findnodes 找不到给定的路径

问题描述

findnodes我有一个关于Perl的简单问题。假设我有以下示例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)中删除其余的解释,即,

版本="2.1" xmlns="http://www.froglogic.com/XML2"

然后一切都好,然后我就有了想要的输出。但如果我在主根中包含上述解释,则不会。

有人知道为什么会这样吗?谢谢!

标签: xmlperl

解决方案


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

Cleaned up:

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

推荐阅读