xml - 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"
然后一切都好,然后我就有了想要的输出。但如果我在主根中包含上述解释,则不会。
有人知道为什么会这样吗?谢谢!
解决方案
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";
推荐阅读
- python-2.7 - Python 2.7 strftime 类型错误
- r - 暂停闪亮会话并返回前端 UI
- jquery - 如何在另一个元素之后附加一个元素?
- jenkins - 错误:无法找到浏览器。“browserstack:Chrome@68.0:Windows 10”不是浏览器别名或可执行文件的路径
- python - 将循环的先前值用于下一个循环
- java - 将 CustomPropertyComparator 与 java.util.List 一起使用
- sql-server - SSRS 部署中的项目设置是什么?
- python - Discord 机器人检查机器人是否删除了消息
- python - 如何在 BeautifulSoup 中找到标签和文本的组合
- https - 在 Web 应用程序中如何以及在何处进行加密?