gpt4 book ai didi

php - XPath 不匹配没有 namespace 作为前缀的属性

转载 作者:可可西里 更新时间:2023-10-31 23:43:35 25 4
gpt4 key购买 nike

目前我正在尝试通过 PHP 的 SimpleXML 读取 Firefox 扩展的不同 install.rdf 文件。

不幸的是,它们的外观没有预定义的结构。他们总是使用两个命名空间,“http://www.w3.org/1999/02/22-rdf-syntax-ns# ”和“http://www.mozilla.org/2004/em-rdf# ”。

所以我的想法是使用 XPath 来获取感兴趣的元素:

$xml = simplexml_load_string($installRDF);
$namespaces = $xml->getNameSpaces(true);
$xml->registerXPathNamespace('rdf', NS_RDF);
$main = $xml->xpath('/rdf:RDF/rdf:Description[@rdf:about="urn:mozilla:install-manifest"]');

但是关于about属性的rdf前缀似乎有问题,因为它只是返回一个结果,如果在RDF文件中也定义了一个前缀.

因此它有效:

<RDF:RDF xmlns:em="http://www.mozilla.org/2004/em-rdf#"
xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#">

<RDF:Description RDF:about="urn:mozilla:install-manifest">
<em:id>extension@mozilla.org</em:id>
</RDF:Description>
</RDF:RDF>

但这不是:

<RDF xmlns:em="http://www.mozilla.org/2004/em-rdf#"
xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#">

<Description about="urn:mozilla:install-manifest">
<em:id>extension@mozilla.org</em:id>
</Description>
</RDF>

在我看来,这看起来像是 PHP 中的一个错误,因为如果我从 XPath 中删除该属性,我总是会得到 Description 元素。但是我还不知道在 XPath 中使用 namespace ,所以我在这里问。

最佳答案

问题是第二个示例中的属性位于空命名空间中。问题不在于查询,而是您的两个示例的 XML 数据不等效。

参见 Namespaces in XML 1.0 (Third Edition) :

A default namespace declaration applies to all unprefixed element names within its scope. Default namespace declarations do not apply directly to attribute names; the interpretation of unprefixed attributes is determined by the element on which they appear.

关于php - XPath 不匹配没有 namespace 作为前缀的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6913202/

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