Parsing XML in Android


Since a lot of API responses are in XML, we'll review XML parsing in Android to help you get to the interesting data faster.

This tutorial assumes that you've already gone through our Android getting started tutorial and are familiar with how our Android SDK works.

Get an XML Response

1 Log in to Temboo and go to the Yahoo > Weather > GetWeatherByAddress Choreo in our Library.

2 Enter a location in the Address input and click 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 Android and pick out only the pieces we're interested in.

Parse it in Android

4 Create a new Java class and copy in the code below. Steps 5 & 6 talk you through what happens in the code.

package com.temboo.android.gettingstarted.app;

import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;

import com.temboo.Library.Yahoo.Weather.GetWeatherByAddress;
import com.temboo.Library.Yahoo.Weather.GetWeatherByAddress.GetWeatherByAddressInputSet;
import com.temboo.Library.Yahoo.Weather.GetWeatherByAddress.GetWeatherByAddressResultSet;
import com.temboo.core.TembooSession;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * An AsyncTask that uses Temboo to retrive the current weather for a given address
 * and then parses the XML response
 */
class XMLTask extends AsyncTask {

	private TextView textView;

	public XMLTask(TextView textView){
		this.textView = textView;
	}

	@Override
	protected String doInBackground(Void... arg0) {
		try {
	 		// Create a new Temboo session.
			TembooSession session = new TembooSession("ACCOUNT_NAME", "APP_NAME", "APP_KEY");
			
			// Instantiate the Yahoo.Weather.GetWeatherByAddress Choreo, using the session object.
			GetWeatherByAddress getWeatherByAddressChoreo = new GetWeatherByAddress(session);

			// Get an InputSet object for the Yahoo.Weather.GetWeatherByAddress Choreo.
			GetWeatherByAddressInputSet getWeatherByAddressInputs = getWeatherByAddressChoreo.newInputSet();

			// Set inputs for the Yahoo.Weather.GetWeatherByAddress Choreo
			getWeatherByAddressInputs.set_Address("104 Franklin St, New York, NY");

			// Execute Yahoo.Weather.GetWeatherByAddress Choreo
			GetWeatherByAddressResultSet getWeatherByAddressResults = getWeatherByAddressChoreo.execute(getWeatherByAddressInputs);

			// Convert response to a w3c.Document object.
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document weatherDocument = builder.parse(
					new InputSource(new ByteArrayInputStream(getWeatherByAddressResults.get_Response().getBytes("utf-8"))));

			// Extract the attribute values for temp and text within the yweather:condition element.
			NodeList conditions = weatherDocument.getElementsByTagName("yweather:condition");
			Element condition = (Element) conditions.item(0);
			String text = condition.getAttribute("text");
			String temperature = condition.getAttribute("temp");

			return temperature + " degrees, " + text;
		} catch(Exception e) {
			// if an exception occurred, log it
			Log.e(this.getClass().toString(), e.getMessage());
		}
		return null;
	}

	protected void onPostExecute(String result) {
		try {
			// Update UI
			textView.setText(result);
		} catch(Exception e) {
			// if an exception occurred, show an error message
			Log.e(this.getClass().toString(), e.getMessage());
		}
	}
}

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 in your Android IDE to try it out. You should see the weather condition text and temp printed to your device's screen.

What next?

Now you're ready to tackle all sorts of XML parsing tasks. Check out the 2000+ Choreos in our Library and find some exciting data to parse.

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.

Need help?

We're always happy to help. Just email us at support@temboo.com, and we'll answer your questions.

We're hiring!

Like what we do? Take a look at our open positions.


Back