Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
722 views
in Technique[技术] by (71.8m points)

ruby on rails - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...