Skip to content

Instantly share code, notes, and snippets.

@xentek
Created February 7, 2012 01:57
Show Gist options
  • Save xentek/1756582 to your computer and use it in GitHub Desktop.
Save xentek/1756582 to your computer and use it in GitHub Desktop.
HTTParty with XML example
require 'httparty'
response = HTTParty.get('http://www.google.com/ig/api?weather=Chicago')
data = response.parsed_response
puts data['xml_api_reply']['weather']['current_conditions']['condition']['data']
require 'httparty'
response = HTTParty.get('http://www.google.com/ig/api?weather=Chicago')
forecast_conditions = response.parsed_response['xml_api_reply']['weather']['forecast_conditions']
forecast_conditions.each do |condition|
puts "The forecast for #{condition['day_of_week']['data']} with a high of #{condition['high']['data']}, and a low of #{condition['low']['data']}. It will be #{condition['condition']['data']}"
end
@xentek
Copy link
Author

xentek commented Feb 7, 2012

  • Don't forget to put httparty in your Gemfile, and run bundle install (or gem install httparty if you're just playing with this in irb)
  • I also recommend that you install/bundle libxml-ruby as well. This is the fastest xml parser that I've found, and if available/required HTTParty will use this automatically.
  • The parsed_response method turns the XML into a ruby hash for you, making it super easy to work with. Else, you'd have to use something like XPath (which is a really neat technology, but kind of a drag to use in practice)
  • XML, like HTML is nested, so you have to work your way down the path to the data you want.

@rubencodes
Copy link

In this example, is forecast_conditions a root node? or is it several nodes? Thanks for this great example!

EDIT: Also, how would you get an attribute vs innerHTML?

@suryapandian
Copy link

For a use case I would like to edit the XML response and make another post request.
What is the best way to go about this?

  1. Should I construct the XML back again from the hash?
  2. Can I somehow get the response in XML format itself and edit the data?

Which would be the better approach?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment