从使用命名空间的XML文档中提取数据
发布时间:2020-12-16 07:50:37 所属栏目:百科 来源:网络整理
导读:我有一些 XML文件,我想从中使用一些信息.我编写了一个代码来读取这些文件,然后查找一些条件. 问题是这些XML文件以 SquishReport version="2.1" xmlns="http://www.froglogic.com/XML2" 并且Perl无法读取它们(至少在我的代码中!).但是当我在XML文件的第一行
我有一些
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:squishtestsources.py" time="2015-02-01T03:45:23+02:00"> <description> <![CDATA[>> >> >> start: init (global) - testcase C:squishtesttst_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(而不是前缀:SquishReport)时,它会尝试匹配null命名空间中名为SquishReport的元素.简而言之,我们可以说它试图匹配一个 {}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文档中使用的前缀(如果有)无关.您需要知道要搜索的元素所在的命名空间,而不是给定文档使用的前缀. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |