Nokogiri 和 XPath 中未定义的命名空间前缀 [英] Undefined namespace prefix in Nokogiri and XPath

查看:63
本文介绍了Nokogiri 和 XPath 中未定义的命名空间前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析 Youtube Gdata 以查看具有给定 ID 的视频是否存在.但是没有普通的标签,而是有命名空间.在链接 http://gdata.youtube.com/feeds/api/videos?q=KgfdlZuVz7I 有标签:

I am trying to parse Youtube Gdata to see if video with given id exists. But there isn't normal tag but with namespace. On the link http://gdata.youtube.com/feeds/api/videos?q=KgfdlZuVz7I there is tag:

<openSearch:totalResults>1</openSearch:totalResults>

有命名空间 openSearch:

There is namespace openSearch:

xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'

但我不知道如何在 Nokogiri 和 Ruby 中处理它.

but I dont know how to deal with it in Nokogiri and Ruby.

这是部分代码:

xmlfeed = Nokogiri::HTML(open("http://gdata.youtube.com/feeds/api/videos?q=#{video_id}"))
xmlfeed.at_xpath("openSearch:totalResults")

它给出了错误:

Undefined namespace prefix: openSearch:totalResults

推荐答案

我不知道为什么,但似乎您必须删除命名空间前缀才能获取节点:

I'm not sure why, but it seems that you have to drop the namespace prefix to get the node:

xmlfeed.at_xpath("//totalresults")

另请注意,我添加了双正斜杠,它将搜索范围限定在整个文档(没有它就无法工作).

Also note that I added the double forward slash, which scopes the search over the whole document (it won't work without it).

更新:

基于这个答案:我如何让 Nokogiri了解我的命名空间? 我猜想命名空间 (openSearch:totalResults) 没有正确声明为文档根节点上的属性,因此 Nokogiri 只是忽略它,这就是为什么上面的选择器有效而命名空间的选择器无效.

Based on this answer: How do I get Nokogiri to understand my namespaces? I'd guess that the namespace (openSearch:totalResults) is not correctly declared as an attribute on the root node of the document, and hence Nokogiri is just ignoring it, which is why the selector above works but the namespaced one doesn't.

这篇关于Nokogiri 和 XPath 中未定义的命名空间前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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