我有一些 XML 文件,我想在其中使用其中的一些信息。我编写了一个代码来读取这些文件,然后查找一些条件。
问题是这些 XML 文件以
开头 <SquishReport version="2.1" xmlns="http://www.froglogic.com/XML2">
并且 Perl 无法读取它们(至少在我的代码中是这样!)。但是当我将这些行附加到 XML
文件的第一行时
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl"?>
效果很好。
我的 XML 文件 test.xml
中的一些行:
<SquishReport version="2.1" xmlns="http://www.froglogic.com/XML2">
<test name="TEST">
<prolog time="2015-10-01T03:45:22+02:00"/>
<test name="tst_start_app">
<prolog time="2015-02-01T03:45:23+02:00"/>
<message line="38" type="LOG" file="C:\squish\test\sources.py" time="2015-02-01T03:45:23+02:00">
<description>
<![CDATA[>> >> >> start: init (global) - testcase C:\squish\test\tst_start_app]]></description>
</message>
</test>
</test>
</SquishReport>
读取 XML 文件的 Perl 代码是:
use strict;
use warnings;
use feature 'say';
use XML::LibXML;
# Parse the XML
my $xml = XML::LibXML->load_xml(location => 'test.xml');
# Iterate the entries
for my $entry ($xml->findnodes('/SquishReport/test/test')) {
my $key = $entry->findvalue('@name');
say "$key";
}
最佳答案
该文档的根节点是 http://www.froglogic.com/XML2
命名空间中名为 SquishReport
的元素。简而言之,我们可以说根节点是一个
{http://www.froglogic.com/XML2}SquishReport
当在 XPath 中使用 SquishReport
(与 prefix:SquishReport
相对)时,会尝试匹配名称为 SquishReport 的元素
在 null 命名空间中。简而言之,我们可以说它试图匹配一个
{}SquishReport
要指定命名空间,可以使用 context 中定义的前缀,如下:
use strict;
use warnings;
use feature qw( say );
use XML::LibXML qw( );
use XML::LibXML::XPathContext qw( );
my $xpc = XML::LibXML::XPathContext->new();
$xpc->registerNs(sr => 'http://www.froglogic.com/XML2');
my $doc = XML::LibXML->load_xml( location => 'test.xml' );
for my $entry ($xpc->findnodes('/sr:SquishReport/sr:test/sr:test', $doc)) {
my $key = $entry->findvalue('@name');
say $key;
}
注意:XPath 中使用的前缀与 XML 文档中使用的前缀(如果有)无关。您应该知道您要搜索的元素所在的命名空间,但不知道给定文档使用的前缀。
关于xml - 从使用 namespace 的 XML 文档中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33370690/