加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – XPath与没有名称空间的属性不匹配作为前缀

发布时间:2020-12-13 22:31:31 所属栏目:PHP教程 来源:网络整理
导读:目前我正在尝试通过 PHP的SimpleXML读取Firefox扩展的不同install.rdf文件. 不幸的是,它们没有预定义的结构. 它们总是使用两个名称空间,“http://www.w3.org/1999/02/22-rdf-syntax-ns#”和“http://www.mozilla.org/2004/em-rdf#”. 所以我的想法是使用XPat
目前我正在尝试通过 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中使用命名空间,所以我在这里问.

解决方法

问题是第二个示例中的属性位于空命名空间中.问题不在于查询,但是两个示例的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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读