gpt4 book ai didi

perl - 在 perl 中使用 xml::Libxml::Xpathcontext 解析具有多个命名空间的 xml

转载 作者:行者123 更新时间:2023-12-03 01:47:56 24 4
gpt4 key购买 nike

我必须解析以下 XML:

<reply xmlns="urn::ietf::param" xmlns:element="https://xml.example.net/abc/12.3"
message-id='1'>
<abc>
<xyz> hello </xyz>
</abc>
</reply>

我想要 xyz 节点的值,即 hello,但 findnodes 返回空值。我的代码是:

 my $xpath=XML::LibXML::XPathContext->new($dom);
$xpath->registerNs('ns1','urn::ietf::param');
$xpath->registerNs('ns2','https://xml.example.net/abc/12.3');
$val=$xpath->findnodes('//ns1:reply/ns2:element/abc/xyz');
print $val;

但是 print 语句返回 null 值

最佳答案

看来您对命名空间的工作原理存在一些误解。 xmlns:element="https://xml.example.net/abc/12.3"表示有前缀 element使用此特定命名空间 URI 定义。实际上,您的 XML 中从未使用过此 namespace 。

xmlns="urn::ietf::param"定义默认 namespace 并且也适用于所有后代元素。实际上你没有<element/> XML 中的元素。

因此,以下 XPath 应按预期工作:

//ns1:reply/ns1:abc/ns1:xyz

关于perl - 在 perl 中使用 xml::Libxml::Xpathcontext 解析具有多个命名空间的 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22936251/

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