SimpleXMLElement::registerXPathNamespace
(PHP 5 >= 5.2.0, PHP 7)
SimpleXMLElement :: registerXPathNamespace - 为下一个XPath查询创建前缀/ ns上下文
描述
public bool SimpleXMLElement::registerXPathNamespace ( string $prefix , string $ns )
为下一个XPath查询创建前缀/ ns上下文。特别是,如果给定XML文档的提供者更改名称空间前缀,这将非常有用。registerXPathNamespace将为关联的命名空间创建一个前缀,允许其访问该命名空间中的节点,而无需更改代码以允许提供者指定的新前缀。
参数
prefix
名称空间前缀在XPath查询中用于ns中给出的名称空间。
ns
用于XPath查询的名称空间。 这必须与XML文档使用的名称空间匹配,否则使用前缀的XPath查询不会返回任何结果。
返回值
成功返回TRUE或失败时返回FALSE。
例子
示例#1 设置要在XPath查询中使用的名称空间前缀
<?php
$xml?=?<<<EOD
<book?xmlns:chap="http://example.org/chapter-title">
????<title>My?Book</title>
????<chapter?id="1">
????????<chap:title>Chapter?1</chap:title>
????????<para>Donec?velit.?Nullam?eget?tellus?vitae?tortor?gravida?scelerisque.?
????????????In?orci?lorem,?cursus?imperdiet,?ultricies?non,?hendrerit?et,?orci.?
????????????Nulla?facilisi.?Nullam?velit?nisl,?laoreet?id,?condimentum?ut,?
????????????ultricies?id,?mauris.</para>
????</chapter>
????<chapter?id="2">
????????<chap:title>Chapter?2</chap:title>
????????<para>Lorem?ipsum?dolor?sit?amet,?consectetuer?adipiscing?elit.?Proin?
????????????gravida.?Phasellus?tincidunt?massa?vel?urna.?Proin?adipiscing?quam?
????????????vitae?odio.?Sed?dictum.?Ut?tincidunt?lorem?ac?lorem.?Duis?eros?
????????????tellus,?pharetra?id,?faucibus?eu,?dapibus?dictum,?odio.</para>
????</chapter>
</book>
EOD;
$sxe?=?new?SimpleXMLElement($xml);
$sxe->registerXPathNamespace('c',?'http://example.org/chapter-title');
$result?=?$sxe->xpath('//c:title');
foreach?($result?as?$title)?{
??echo?$title?.?"\n";
}
?>
上面的例子将输出:
Chapter 1
Chapter 2
请注意,示例中显示的XML文档如何设置名称空间,其前缀为chap。想象一下,这个文档(或者另一个喜欢它的文档)在过去可能为同一个命名空间使用了c的前缀。由于它已更改,XPath查询将不再返回正确的结果,并且查询将需要修改。使用registerXPathNamespace 可以避免将来对该查询进行修改,即使提供者更改了命名空间前缀。
扩展内容
- SimpleXMLElement :: xpath() - 对XML数据运行XPath查询
- SimpleXMLElement :: getDocNamespaces() - 返回在文档中声明的名称空间
- SimpleXMLElement :: getNamespaces() - 返回文档中使用的名称空间
← SimpleXMLElement::getNamespaces
SimpleXMLElement::saveXML →
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com