2012-10-17 64 views
0

我基本上試圖從我對ChartLyrics API的響應中獲取Lyric標記。這裏是我寫的代碼:Rails:無法使用Nokogiri解析XML響應

require 'nokogiri' 
require 'open-uri' 

request = Net::HTTP.get(URI.parse('http://api.chartlyrics.com/apiv1.asmx/GetLyric?lyricId=1710&lyricCheckSum=a4a56a99ee00cd8e67872a7764d6f9c6')) 
puts request 
response = Nokogiri::XML(request) 

puts response.xpath("//Lyric")[0].to_s 

我已閱讀文檔,但沒有找到答案。我在這裏做錯了什麼?

回答

1

試試下面的代碼

require 'open-uri' 
require 'nokogiri' 
xml_doc = Nokogiri::XML(open('http://api.chartlyrics.com/apiv1.asmx/GetLyric?lyricId=1710&lyricCheckSum=a4a56a99ee00cd8e67872a7764d6f9c6')) 
#I always prefer css than xpath 
lyrics = xml_doc.css('Lyric') 
if lyrics.empty? 
    puts "COuld not find any lyric in the XML document' 
else 
    puts lyrics[0].to_s 
end 
+0

非常感謝!還有一個問題。是否可以從'lyrics'參數中刪除「Lyric」標籤? – Ali

+0

對不起,我找不到你? –

+0

沒問題。我修好了它。非常感謝回覆。 – Ali

1

做response.remove_namespaces! before response.xpath