hamadata's diary

https://motion-gallery.net のエンジニアのブログ

じゃらんのエリア検索

Rubyで書いてみた。

require 'rexml/document'
require 'open-uri'

uri_area="http://jws.jalan.net/content/data/area.xml"
x_area = REXML::Document.new(open(uri_area){|f| f.read})

h_s_area = Hash.new
x_area.elements.each('Area/Prefecture/LargeArea/SmallArea/') do |elem|
  h_s_area[elem.attributes["cd"]] = elem.attributes["name"]
end

#puts h_s_area

hr_s_area = Hash.new

h_s_area.each_pair do |key, value|
  hr_s_area[value] = key
end

puts hr_s_area

わざわざ逆のハッシュつくるのに余計なことはしなくてよいことに気づく。

require 'rexml/document'
require 'open-uri'

uri_area="http://jws.jalan.net/content/data/area.xml"
x_area = REXML::Document.new(open(uri_area){|f| f.read})

h_s_area = Hash.new
hr_s_area = Hash.new
x_area.elements.each('Area/Prefecture/LargeArea/SmallArea/') do |elem|
  h_s_area[elem.attributes["cd"]] = elem.attributes["name"]
  hr_s_area[elem.attributes["name"]] = elem.attributes["cd"]
end

h_l_area = Hash.new
hr_l_area = Hash.new
x_area.elements.each('Area/Prefecture/LargeArea/') do |elem|
  h_l_area[elem.attributes["cd"]] = elem.attributes["name"]
  hr_l_area[elem.attributes["name"]] = elem.attributes["cd"]
end

h_p_area = Hash.new
hr_p_area = Hash.new
x_area.elements.each('Area/Prefecture/') do |elem|
  h_p_area[elem.attributes["cd"]] = elem.attributes["name"]
  hr_p_area[elem.attributes["name"]] = elem.attributes["cd"]
end

と思ったら、RailsのHashには、from_xmlというメソッドが実装されているのを発見。

@h_result = Hash.new
@h_result = Hash.from_xml(open('filename'){|f| f.read})