2007/12/22

iTunes-playlist-output.xml

iTunesplaylistを選択-iTunesメニュー-ファイル-書き出し-Unicodeテキスト
を選択した結果のテキストどれも全く気に入らないので、XML書き出したのを整形。

# 自分で作成した playlist の曲をよみやすいテキストに書き出す.一歩手前
# playlist.rb

require 'rexml/document'

class BaseXML

  attr_accessor :doc

  def initialize(path=nil)
    @doc = readxml(path) unless path.nil?
  end

  def readxml(path)
    return nil unless FileTest.exist?(path)
    return REXML::Document.new(IO.read(path)) unless path.nil?
  end

  def key?(xpath)
    return true unless @doc.root.elements[xpath].nil?
    return false
  end

  def lookup(xpath)
    return nil unless key?(xpath)
    if @doc.root.get_elements(xpath).size == 1
      @doc.root.elements[xpath]
    else
      @doc.root.get_elements(xpath)
    end
  end

end

def one(song)
  h = Hash.new
  begin
    song.each{|x| h[x.text] ||= x.next_element.text}
  rescue
  end
  trackID = h['Track ID']
  @playlist[trackID] = [h['Name'], " / ", h['Album'], " -", h['Artist']]
end

@playlist = Hash.new
xml = BaseXML.new('output.xml')
list = xml.lookup('dict/dict/dict').each{|k| }
list.each{|x|
  song = x.to_a.select{|i| i.class.to_s =~ /REXML::Element/}
  one(song)
}

iid = xml.lookup('dict/array/dict/array/dict/integer')
iid.select{|x| x.class.to_s =~ /REXML::Element/}
iid.each{|x|
  print @playlist[x.text]
  print "\n"
}
exit

% /usr/local/bin/ruby playlist.rb > output.txt


+++ memo +++

iTunes-ファイル-書き出し が書き出す XML の特徴。

document root からたどって <dict><dict> の配下にある <dict> 要素におさめられているのが一曲分。
一曲分の要素は <key>or<integer>or<string> のいずれかで構成されている。

 <dict>
 <key>Track ID</key><integer>2314</integer>
 <key>Name</key><string>イエロー・マジック・カーニバル</string>
 <key>Artist</key><string>Van Dyke Parks</string>
 <key>Composer</key><string>細野晴臣</string>
 <key>Album</key><string>細野晴臣トリビュート・アルバム Tribute to Haruomi Hosono [Disc 1]</string>
 <key>Genre</key><string>ポップ</string>
 <key>Kind</key><string>AAC オーディオファイル</string>
 ...
 </dict>


例えば、doc.root.elements['dict/dict/dict/Artist'] としても ”Van Dyke Parks” は得られないから
h['Artist'] で呼び出しができるように一旦ハッシュにした。

xpath='dict/array/dict/array/dict/integer'には曲固有のID番号がふってある。path='dict/array/dict/array/dict/integer'の'integer' 要素の順番が曲順であって
xpath='dict/dict/dict'の順番とは無関係。

--imported_from
http://www.midore.net/daybook/2007/12/1198249205.html

0 件のコメント: