Since a lot of API responses are in XML, we'll review XML parsing in Ruby to help you get to the interesting data faster.
This tutorial assumes that you've already gone through our Ruby getting started tutorial and are familiar with how our Ruby SDK works.
1 Log in to Temboo and go to the Yahoo > Weather > GetWeatherByAddress Choreo in our Library. Select Ruby from the drop down menu at the top of the page.
2 Enter a location in the Address input and click Generate Code to test the Choreo from our website.
3 You get a whole bunch of XML in the Response output with lots of weather-related information about the location. Next we'll see how to parse through this response in Ruby and pick out only the pieces we're interested in.
4 Create a new Ruby class and copy in the code below. Steps 5 & 6 talk you through what happens in the code.
require "rexml/document" require "rexml/xpath" require "temboo" require "Library/Yahoo" class XMLExample def initialize() @session = TembooSession.new("ACCOUNT_NAME", "APP_NAME", "APP_KEY") end def parse_weather_data() weather_choreo = Yahoo::Weather::GetWeatherByAddress.new(@session) # Get an InputSet object for the choreo weather_inputs = weather_choreo.new_input_set() # Set inputs weather_inputs.set_Address("104 Franklin St, New York, NY") # Execute Choreo weather_results = weather_choreo.execute(weather_inputs) document = REXML::Document.new(weather_results.get_Response()) condition = REXML::XPath.first(document, '//ytweather:condition', {'ytweather' => 'http://xml.weather.yahoo.com/ns/rss/1.0'}) # Salient information about the condition are stored in its attributes. Get a hash of them. attributes = condition.attributes() # Using the fields of your condition attribute hash, get some info about the weather. printf("Conditions are %s with a temperature of %s.\n", attributes['text'], attributes['temp']) end end instance = XMLExample.new() instance.parse_weather_data()
5 First we have to convert the XML response from Yahoo to a w3c.Document object.
6 Next we need to parse out the data we want from the XML file. It helps to look at the XML file's structure to get an idea of how it is organized. We want the text and temp attributes. You can find them in:
<channel><yweather:condition>
.
7That's it. You can run the code to try it out. You should see a message bout the weather condition including its text and temp printed in the console.
Now you're ready to tackle all sorts of XML parsing tasks. You can find tons of Choreos that return XML in our Library.
Once you've got your code up and running, you're ready to move on and do more. From monitoring your running applications, to moving your generated Temboo code to your preferred development environment and sharing it with colleagues, collaborators and friends - we've got you covered.
We're always happy to help. Just email us at support@temboo.com, and we'll answer your questions.
Like what we do? Take a look at our open positions.