Created
February 7, 2012 01:57
-
-
Save xentek/1756582 to your computer and use it in GitHub Desktop.
HTTParty with XML example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
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?
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?
- Should I construct the XML back again from the hash?
- 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
httpartyin your Gemfile, and runbundle install(orgem install httpartyif you're just playing with this inirb)libxml-rubyas well. This is the fastest xml parser that I've found, and if available/required HTTParty will use this automatically.parsed_responsemethod 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)