Fetching XML in rails (using REXML)

require ‘net/http’
require ‘rexml/document’
url = “http://maps.google.com/maps/api/directions/xml?key=*************************&sensor=false&origin=Chennai&destination=Trichy”
# get the XML data as a string
xml_data = Net::HTTP.get_response(URI.parse(url)).body
# extract event information
doc = REXML::Document.new(xml_data)
duration = []
way = []
kms=[]
full_text=[]
doc.elements.each(‘DirectionsResponse/route/leg/step/html_instructions’) do |a|
way<<a.text
end
doc.elements.each(‘DirectionsResponse/route/leg/step/distance/text’) do |a|
kms<<a.text
end
doc.elements.each(‘DirectionsResponse/route/leg/step/duration/text’) do |a|
duration<<a.text
end
way.each_with_index do|text, index|
full_text<<“#{kms[index]}(#{duration[index]})—>#{way[index]}<br/>”
end
@full_text=full_text

Advertisements