0

我正在从事个人项目并使用 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')
=> []

“歌词”每次都是零。谁能告诉我我做错了什么?谢谢

4

1 回答 1

3

默认情况下,nokogiri 会查找不在任何命名空间中的元素,但此文档是有命名空间的:

doc.namespaces
#=> {"xmlns:xsi"=>"http://www.w3.org/2001/XMLSchema-instance", "xmlns:xsd"=>"http://www.w3.org/2001/XMLSchema", "xmlns"=>"http://api.chartlyrics.com/"}

因此,您必须将xmlns命名空间附加到您正在搜索的标签(您可以省略实际的 URL,因为nokogiri 将为您填写默认命名空间的 URL):

doc.xpath('//xmlns:Lyric')

或者,您可以使用 css 进行搜索:

doc.css('Lyric')

另请参阅:为什么 Nokogiri xpath 不像 xmlns 声明

于 2012-10-09T04:26:53.757 回答