2012-09-14 50 views
0

正常查詢到的Youtube GDATA API爲特定的視頻是這樣的:引入nokogiri:檢查是否命名空間存在

http://gdata.youtube.com/feeds/api/videos?q=H-x7UumBaFs

返回這樣的結果:

<?xml version="1.0" encoding="UTF-8"?> 
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:yt="http://gdata.youtube.com/schemas/2007"> 
<!-- data --> 
<entry> 
<!-- data --> 
<gd:rating average="3.2309198" max="5" min="1" numRaters="511" rel="http://schemas.google.com/g/2005#overall"/> 
</entry> 
</feed> 

但是有時GD :評級線不存在。

我想從該行讀取數據(如果存在)。我試圖檢查此:

if node.at_xpath(".//gd:rating/@numRaters") 

但是,這並不工作,讓錯誤「未定義命名空間前綴:.//gd:rating/@numRaters」

你知道我怎麼能在讀取之前檢查gd:rating命名空間的存在性?

回答

0

由於this questionNokogiri docs,這是對我工作的解決方案:

gd_namespace = {"xmlns:gd" => "http://schemas.google.com/g/2005"} 

... 

s.num_raters = node.at_xpath('.//gd:rating/@numRaters', gd_namespace).try(:text) 
相關問題