我正在从事个人项目并使用 Rails 来学习框架。该项目是基于音乐的,我正在使用 ChartLyrics.com 的 API 来检索歌词。API 返回 XML,我无法从 XML 中提取实际的歌词元素。
我已经安装了 Nokogiri gem 来帮助解析 XML。以下是我用来检索数据的内容。从 rails 控制台:
doc = Nokogiri::XML(open(http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad))
puts doc
<?xml version="1.0" encoding="utf-8"?>
<GetLyricResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://api.chartlyrics.com/">
<TrackId>0</TrackId>
<LyricChecksum>a4a56a99ee00cd8e67872a7764d6f9c6</LyricChecksum>
<LyricId>1710</LyricId>
<LyricSong>Bad</LyricSong>
<LyricArtist>Michael Jackson</LyricArtist>
<LyricUrl>http://www.chartlyrics.com/28h-8gWvNk-Rbj1X-R7PXg/Bad.aspx</LyricUrl>
<LyricCovertArtUrl>http://ec1.images-amazon.com/images/P/B000CNET66.02.MZZZZZZZ.jpg</LyricCovertArtUrl>
<LyricRank>9</LyricRank>
<LyricCorrectUrl>http://www.chartlyrics.com/app/correct.aspx?lid=MQA3ADEAMAA=</LyricCorrectUrl>
<Lyric>
Because I'm bad (bad-bad), I'm bad, come on (really, really bad)
You know I'm bad (bad-bad), I'm bad, you know it (really, really bad)
You know I'm bad (bad-bad), I'm bad, you know it (really, really bad) you know
And the whole world has to answer right now
Just to tell you once again
</Lyric>
</GetLyricResult>
我缩短了歌词以节省空间。如何提取“歌词”元素?我已经尝试了以下所有方法:
> lyrics = doc.xpath('//Lyric')
=> []
> lyrics = doc.xpath('/Lyric')
=> []
> lyrics = doc.xpath('//GetLyricResult/Lyric')
=> []
> lyrics = doc.xpath('//GetLyricResult//Lyric')
=> []
> lyrics = doc.xpath('/GetLyricResult/Lyric')
=> []
“歌词”每次都是零。谁能告诉我我做错了什么?谢谢