簡體   English   中英

在Ruby中使用Nokogiri錯誤地解析xml

[英]Incorrectly parsing xml with Nokogiri in Ruby

我正在使用Nokogiri來解析last.fm中的XML響應。 我目前正在返回我想要的信息,但不是我想要的格式。 我得到的似乎是一個Nokogiri :: XML文檔。 我想要的是每個<track>的一行,包括歌曲的標題,藝術家和網址。 以下是XML的示例:

<lfm status="ok">
  <toptracks metro="Beijing" page="1" perPage="50" totalPages="10" total="500">
    <track rank="1">
      <name>Rolling in the Deep</name>
      <duration>226</duration>
      <listeners>33</listeners>
      <mbid>092a88bc-af0b-4ddd-a3a1-17ad37abfccb</mbid>
      <url>
        http://www.last.fm/music/Adele/_/Rolling+in+the+Deep
      </url>
      <streamable fulltrack="0">1</streamable>
      <artist>
        <name>Adele</name>
        <mbid>1de93a63-3a9f-443a-ba8a-a43b5fe0121e</mbid>
        <url>http://www.last.fm/music/Adele</url>
      </artist>
      <image size="small">http://userserve-ak.last.fm/serve/34s/55125087.png</image>
      <image size="medium">http://userserve-ak.last.fm/serve/64s/55125087.png</image>
      <image size="large">http://userserve-ak.last.fm/serve/126/55125087.png</image>
      <image size="extralarge">
        http://userserve-ak.last.fm/serve/300x300/55125087.png
      </image>
    </track>
  </toptracks>
</lfm>

這是我正在使用的代碼:

doc = Nokogiri::HTML(open(url))

doc.xpath("//toptracks").each do |track|
  song_title = track.xpath("*/name").text
  song_lastfm_url = track.xpath("*/url").text
  song_artist = track.xpath("*/artist/name").text

  puts "#{song_title} - #{song_lastfm_url} - #{song_artist}"
end

正如我所提到的,雖然我得到了所有的歌曲標題,然后是所有的歌曲網址,然后是所有的歌曲藝術家作為一個XML文檔。

你不是像你想象的那樣在軌道上迭代。 試試這樣:

doc.xpath('//toptracks/track').each do |track|
  song_title, song_lastfm_url, song_artist = track.xpath('./name','./url','./artist/name').map{|x| x.text.strip}
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM