gpt4 book ai didi

perl - 存在 xmlns 时,XML::LibXML findnodes() 不返回结果

转载 作者:行者123 更新时间:2023-12-01 22:03:53 26 4
gpt4 key购买 nike

我正在使用 XML::LibXML::Reader 解析大型文档,遇到了属性 xmlns 导致 findnodes() 失败的问题。我通过添加正则表达式来删除 xmls 属性来修复它,但我想知道是否有更优雅的解决方案不涉及正则表达式。如果删除正则表达式行 ($xml =~ s{xmlns...),您会看到“Loc = $loc”不会产生任何结果。

代码如下:

use strict;
use warnings;
use feature qw( say );
use XML::LibXML::Reader qw( XML_READER_TYPE_ELEMENT );

my $xml = <<'__EOI__';
<url xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<loc>http://example.com</loc>
<lastmod>2018-10-19</lastmod>
</url>
__EOI__


$xml =~ s{xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"}{};

my $reader = XML::LibXML::Reader->new( string => $xml);
while ( $reader->read ) {
next unless $reader->nodeType == XML_READER_TYPE_ELEMENT;
next unless $reader->name eq 'url';
my $xml = $reader->readOuterXml;
my $doc = XML::LibXML->load_xml(string => $xml);
say "Doc = $doc";
my ($loc) = $doc->findnodes('//loc');
say "Loc = $loc";
}

最佳答案

您要求查找 namespace 为 null 且名称为 loc 的节点。文档中没有这样的节点,因此 findnodes 正确地不返回任何内容。

您想要查找具有命名空间 http://www.sitemaps.org/schemas/sitemap/0.9 和名称 loc 的节点。您可以使用以下方法来实现:

my $doc = XML::LibXML->load_xml( string => $xml );

my $xpc = XML::LibXML::XPathContext->new();
$xpc->registerNs( sm => 'http://www.sitemaps.org/schemas/sitemap/0.9' );

my ($loc) = $xpc->findnodes('//sm:loc', $doc);

关于perl - 存在 xmlns 时,XML::LibXML findnodes() 不返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52905726/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com