如果元素具有xmlns属性,则Xpath失败 [英] Xpath fails if an element has a a xmlns attribute

查看:99
本文介绍了如果元素具有xmlns属性,则Xpath失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
xPath除了*

Possible Duplicate:
xPath finds nothing but *

我正在尝试使用xml解析.COLLADA文件.问题是,如果根标记具有xmlns属性,我似乎无法使用xpath()来访问元素.

Im trying to use xml to parse a .COLLADA file. The problem is I can't seem to use xpath() to access elements if the root tag has a xmlns attribute.

例如,这可行:

$string = <<<TEST
<?xml version="1.0" encoding="utf-8"?>
<COLLADA version="1.4.1">
  <library_materials>
    <material id="Material" name="Material">
      <instance_effect url="#Material-effect"/>
    </material>
    <material id="Material2" name="Material">
      <instance_effect url="#Material-effect2"/>
    </material>
  </library_materials>
</COLLADA>
TEST;
$lol = new SimpleXMLElement($string);
print_r($lol->library_materials->xpath("material[@id='Material2']"));

但这不是:

$string = <<<TEST
<?xml version="1.0" encoding="utf-8"?>
<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">
  <library_materials>
    <material id="Material" name="Material">
      <instance_effect url="#Material-effect"/>
    </material>
    <material id="Material2" name="Material">
      <instance_effect url="#Material-effect2"/>
    </material>
  </library_materials>
</COLLADA>
TEST;
$lol = new SimpleXMLElement($string);
print_r($lol->library_materials->xpath("material[@id='Material2']"));

xmlns如何突然使xml树不可用?我认为它只是定义了名称空间,因此您可以将其与其他名称空间中的其他相同标签区分开.我想念什么?

How does the xmlns suddenly make the xml tree unusable? I thought it just defined the namespace so you could tell it apart from other identical tags in other namespaces. What am I missing?

推荐答案

您需要注册名称空间:

$lol = new SimpleXMLElement($string);
$lol->registerXPathNamespace('cada', 'http://www.collada.org/2005/11/COLLADASchema');
print_r($lol->xpath("child::cada:library_materials//*[@id='Material2']"));

这篇关于如果元素具有xmlns属性,则Xpath失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆