Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined namespace prefix in Nokogiri and XPath

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>

There is namespace openSearch:

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

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

Here is part of code:

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

It gives error:

Undefined namespace prefix: openSearch:totalResults
like image 216
Иван Бишевац Avatar asked Sep 18 '12 02:09

Иван Бишевац


1 Answers

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).

UPDATE:

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.

like image 60
Chris Salzberg Avatar answered Sep 28 '22 00:09

Chris Salzberg