1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
require 'net/http' require 'rubygems' require 'xmlsimple' AYWT_URL = 'http://areyouwatchingthis.com/api/games/' def get_data(endpoint) XmlSimple.xml_in(Net::HTTP.get_response(URI.parse([AYWT_URL,endpoint].join)).body) end def get_games_for_sport(sport) # http://areyouwatchingthis.com/api/games?sport=mlb&sport=cfl get_data("?sport=#{sport}") end def get_game_details(game_id) get_data("?gameID=#{game_id}") end @game_information = get_game_details(76513) @game_information["games"].each do |games| games["game"].each do |game| game["teams"].each do |teams| teams["team"].each do |team| p "Team: #{team["name"]} -> City: #{team["city"]}" end end end end # Outputs: # "Team: Rays -> City: Tampa Bay" # "Team: Cardinals -> City: St. Louis"
Refactorings
No refactoring yet !
dreamhost promo code
May 21, 2008, May 21, 2008 03:32, permalink
Well done code dude.
My concern is having three nested do.. each statements which is so time consuming. Right?
mwilliams
May 21, 2008, May 21, 2008 11:26, permalink
Well, it works, but my familiarity with XML isn't the best. I would have preferred to use an XPath based parser of some sort and quickly looked at some other options like REXML and Hpricot but since I do have the knowledge to iterate hashes I just went this route (which wasn't too bad actually) and the performance is pretty solid.
slothbear.myopenid.com
May 22, 2008, May 22, 2008 04:16, permalink
Someone can probably clean up the way I've accessed the text elements, but this starts to show the power of XPath.
1 2 3 4 5 6 7 8 9 10
require 'rexml/document' body = "<your xml stuff>" doc = REXML::Document.new(body) game = REXML::XPath.first(doc, "(//game)[@id=76513]") REXML::XPath.each(game, "//team") do |team| p "Team: #{team.elements['name'].text} -> #{team.elements['city'].text}" end
I'm working with a web service and I don't know if it's my inexperience with parsing XML or working with Ruby Hashes but it seems like I have to jump through a lot of hoops to pull the data out. So if anyone has any improved way to parse out the various elements, feel free to chime in :)
You can view the XML document here: http://areyouwatchingthis.com/api/games?gameID=76513