简单的xpath问题让我抓狂


Simple xpath question that drives me crazy

下面是我使用此xpath打印内容的提要的结构
$xml->xpath('/rss/channel//item')

结构

<rss><channel><item><pubDate></pubDate><title></title><description></description><link></link><author></author></item></channel></rss>

然而,我的一些文件遵循这种结构

<feed xmlns="http://www.w3.org/2005/Atom" .....><entry><published></published><title></title><description></description><link></link><author></author></entry></feed>

我猜测这应该是获取条目内容的xpath

$xml->xpath('/feed//entry')

证明我错了的事情。

我的问题是使用什么是正确的xpath?我是不是错过了什么?

这是代码

<?php
$feeds = array('http://feeds.feedburner.com/blogspot/wSuKU');

$entries = array();
foreach ($feeds as $feed) {
    $xml = simplexml_load_file($feed);
    $entries = array_merge($entries, $xml->xpath('/feed//entry'));
}
echo "<pre>"; print_r($entries); echo"</pre>";
?>

试试这个:

$xml->registerXPathNamespace('f', 'http://www.w3.org/2005/Atom');
$xml->xpath('/f:feed/f:entry');

如果您想要一个在应用于RSS或ATOM提要时可以工作的XPath表达式,可以使用以下任何一个XPath表达式:

这个是最精确的,但也是最冗长的:

(/rss/channel/item 
  | /*[local-name()='feed' and namespace-uri()='http://www.w3.org/2005/Atom']
      /*[local-name()='entry' and namespace-uri()='http://www.w3.org/2005/Atom'])

这个忽略了ATOM元素的名称空间,只匹配它们的local-name():

(/rss/channel/item | /*[local-name()='feed']/*[local-name()='entry'])

这是最简单、但最不精确、效率最低的:

/*//*[local-name()='item' or local-name()='entry']