为什么xpath不返回此XML节点?

时间:2012-06-04 02:27:33

标签: ruby xml nokogiri

所以我的代码看起来像这样:

content_url = 'http://auburn.craigslist.org/cpg/index.rss'
doc = Nokogiri::XML(open(content_url))
bq = doc.xpath('//item')

但它将bq返回为空。

我确信它有这个标签,但这是该页面上的前几个标签:

<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://purl.org/rss/1.0/" xmlns:ev="http://purl.org/rss/1.0/modules/event/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:syn="http://purl.org/rss/1.0/modules/syndication/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:admin="http://webns.net/mvcb/">
<channel rdf:about="http://auburn.craigslist.org/cpg/index.rss">...</channel>
<item rdf:about="http://auburn.craigslist.org/cpg/3012277218.html">...</item>

思想?

2 个答案:

答案 0 :(得分:5)

由于 item 不在默认命名空间中,因此您需要告诉XPath在哪个命名空间下查看。

首先,您的命名空间是xmlns属性设置的名称。对于Craigslist,它似乎是http://purl.org/rss/1.0/。这就是你要告诉XPath要使用的名称空间。

当调用XPath时,我们必须指定我们想要使用的额外命名空间。像这样。

doc.xpath('//item', { 'rdf' => 'http://purl.org/rss/1.0/' })

但不是这样,我们需要告诉XPath该项目在rdf名称空间下。我们可以通过在标记名称前加上命名空间来做到这一点。像这样。

doc.xpath('//rdf:item', { 'rdf' => 'http://purl.org/rss/1.0/' })

答案 1 :(得分:3)

它与名称空间有关。你可以这样做:

doc.remove_namespaces!

或者您可以使用

doc.css('item')

代替

相关问题