问题描述
我有两个问题.让 XPATH 使用 atom 命名空间并从 CDATA 字段获取数据.
I'm having two problems. Getting XPATH to work with atom namespace and getting data from a CDATA field.
我拥有的 xml 看起来像
The xml that I have looks like
<?xml version="1.0" encoding="UTF-8" ?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:kml="http://www.opengis.net/kml/2.2">
<title type="text"><![CDATA[Hello World]]></title>
</entry>
虽然我的 PHP 看起来像
While my PHP looks like
$xml = new SimpleXMLElement(file_get_contents($this->xmlFile));
$xml->setAttributeNS( "http://www.w3.org/2005/Atom");
$xml->registerXpathNamespace('kml' , 'http://www.opengis.net/kml/2.2');
$result = $xml->xpath('/entry/title');
var_dump($result);
从 XML 中删除 atom 命名空间允许我的 xpath 工作.但是如何让 simplexml 接受原子作为命名空间?此外,当我获取数据(没有原子)时,我无法获取文本,因为它的格式为 CDATA,我如何才能显示 CDATA 文本?
Removing the atom namespace from the XML allows my xpath to work. But how do I get simplexml to accept atom as a namespace?Also when I do get data (without atom) I can't get the text because it's formatted as CDATA, how can I get show the CDATA text?
推荐答案
来自 PHP 文档 (http://us1.php.net/manual/en/domelement.setattributens.php):
From the PHP documentation (http://us1.php.net/manual/en/domelement.setattributens.php):
将具有命名空间 namespaceURI 和名称 name 的属性设置为给定值.如果该属性不存在,则会创建该属性.
你不想设置命名空间,但你想声明它以便你可以使用它,所以改变:
You do not want to set a namespace, but you want to declare it so you can use it, so change:
$xml->setAttributeNS( "http://www.w3.org/2005/Atom");
致:
$xml->registerXpathNamespace('atom' , 'http://www.w3.org/2005/Atom');
之后,您可以在 XPath 中使用该前缀:
After that you can use that prefix into your XPath:
$result = $xml->xpath('/atom:entry/atom:title');
这篇关于带有原子命名空间的 XPATH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!