Android: Simple XML SAX Parser Tutorial

7 September 2012 By Nithya Vasudevan 54,349 views 23 Comments
35 Flares Twitter 0 Facebook 23 Google+ 12 35 Flares ×

Project Description

  • This Android example shows how to parse a simple XML containing employee details using SAX parser and display the result in Spinner.
  • This example stores XML file in project’s assets folder and opens the file as InputStream using AssetManager.
  • On button click event, we parse the XML and display employee id and name in Spinner and when an item is selected, complete employee detail is displayed in a Toast message.

To parse an XML in Android, you can use DOM and SAX parser API provided by Java platform. In addition to these two parsers, Android provides XmlPullParser which is similar to StAX parser and is also the recommended parser to use in Android.

Environment Used

  • JDK 6 (Java SE 6)
  • Eclipse Indigo IDE for Java EE Developers (3.7.1)
  • Android SDK 4.0.3 / 4.1 Jelly Bean
  • Android Development Tools (ADT) Plugin for Eclipse (ADT version 20.0.0)
  • Refer this link to setup the Android development environment


Create Android Project

  • Create a new Android Project and name it as SimpleSAXParser.
  • Enter the package name as
  • Enter the Activity name as SAXParserActivity.
  • Click Finish.

Create XML file

In the project’s assets folder, create a new XML file and name it as “employees.xml” and copy the following.

<?xml version="1.0" encoding="UTF-8"?>
		<email>[email protected]</email>
		<email>[email protected]</email>
		<email>[email protected]</email>


Open res/values/string.xml and replace it with following content.

    <string name="app_name">SimpleSAXParser</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_saxparser">SAXParserActivity</string>
    <string name="button">Parse XML using SAX</string>


Open res/values/styles.xml and replace it with following content.

<resources xmlns:android="">
    <style name="AppTheme" parent="@android:style/android:Theme" />
    <style name="spinner">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">fill_parent</item>
        <item name="android:textColor">#0000CD</item>
        <item name="android:text">15dp</item>
        <item name="android:typeface">monospace</item>
        <item name="android:maxHeight">35dp</item>
        <item name="android:paddingTop">5dp</item>
        <item name="android:paddingBottom">8dp</item>

XML layout files

main layout file (main.xml)

This file defines a layout for displaying the result of SAX parser in Spinner widget. Open main.xml file in res/layout and copy the following content.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
        android:text="@string/button" />

Spinner item layout file (list_item.xml)

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android=""
    style="@style/spinner" />

This layout file uses style named “spinner” defined in styles.xml file.

Create Bean class

Create a new Java class “” in package “” and copy the following code.


public class Employee {
	private String name;
	private int id;
	private String department;
	private String type;
	private String email;

	public String getName() {
		return name;

	public void setName(String name) { = name;

	public int getId() {
		return id;

	public void setId(int id) { = id;

	public String getDepartment() {
		return department;

	public void setDepartment(String department) {
		this.department = department;

	public String getType() {
		return type;

	public void setType(String type) {
		this.type = type;

	public String getEmail() {
		return email;

	public void setEmail(String email) { = email;

	public String toString() {
		return id + ": " + name;

	public String getDetails() {
		String result = id + ": " + name + "\n" + department + "-" + type
				+ "\n" + email;
		return result;

Create SAXXMLHandler class

Create a new Java class “” in package “” and copy the following code.


import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXXMLHandler extends DefaultHandler {

	private List<Employee> employees;
	private String tempVal;
	private Employee tempEmp;

	public SAXXMLHandler() {
		employees = new ArrayList<Employee>();

	public List<Employee> getEmployees() {
		return employees;

	// Event Handlers
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// reset
		tempVal = "";
		if (qName.equalsIgnoreCase("employee")) {
			// create a new instance of employee
			tempEmp = new Employee();

	public void characters(char[] ch, int start, int length)
			throws SAXException {
		tempVal = new String(ch, start, length);

	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (qName.equalsIgnoreCase("employee")) {
			// add it to the list
		} else if (qName.equalsIgnoreCase("id")) {
		} else if (qName.equalsIgnoreCase("name")) {
		} else if (qName.equalsIgnoreCase("department")) {
		} else if (qName.equalsIgnoreCase("type")) {
		} else if (qName.equalsIgnoreCase("email")) {

SAX (Simple API for XML) is an event-based sequential access parser API with number of callback methods that will be called when events like start element, end element, attributes etc occur during parsing. This class parses a XML file containing employee details and stores in a list as an employee object.

Create SAXXMLParser class

Create a new Java class “” in package “” and copy the following code.


import java.util.List;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.util.Log;

public class SAXXMLParser {
	public static List<Employee> parse(InputStream is) {
		List<Employee> employees = null;
		try {
			// create a XMLReader from SAXParser
			XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
			// create a SAXXMLHandler
			SAXXMLHandler saxHandler = new SAXXMLHandler();
			// store handler in XMLReader
			// the process starts
			xmlReader.parse(new InputSource(is));
			// get the `Employee list`
			employees = saxHandler.getEmployees();

		} catch (Exception ex) {
			Log.d("XML", "SAXXMLParser: parse() failed");

		// return Employee list
		return employees;

Create SAXParserActivity class

Now lets create the activity class “SAXParserActivity” in package “”.


import java.util.List;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class SAXParserActivity extends Activity implements
		OnClickListener, OnItemSelectedListener {

	Button button;
	Spinner spinner;
	List<Employee> employees = null;

	public void onCreate(Bundle savedInstanceState) {


	private void findViewsById() {
		button = (Button) findViewById(;
		spinner = (Spinner) findViewById(;

	public void onClick(View v) {
		try {
			employees = SAXXMLParser.parse(getAssets().open("employees.xml"));
			ArrayAdapter<Employee> adapter = new ArrayAdapter<Employee>(this,
					R.layout.list_item, employees);
		} catch (IOException e) {

	public void onItemSelected(AdapterView<?> parent, View view, int pos,
			long id) {
		Employee employee = (Employee) parent.getItemAtPosition(pos);
		Toast.makeText(parent.getContext(), employee.getDetails(),

	public void onNothingSelected(AdapterView<?> arg0) {



<manifest xmlns:android=""
    android:versionName="1.0" >

        android:targetSdkVersion="15" />

        android:theme="@style/AppTheme" >
            android:label="@string/title_activity_saxparser" >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />



Run your application

Project Folder Structure

The complete folder structure of this example is shown below.

Tags: , , , , , , , , , , , , , , , , , , , ,

  • jerald

    nice article. thanks

  • venugopal

    Thanks for giving this tutorial with good explanation but I want to parse xml file from offline and I want to display in two spinners please help me for getting the data my xml format is

    - – - – No clients are available No Vendors are available Successful masterdata fetch – - – 41424 Food false false – 43084 Office Maintenance false false

    – 35 British Pounds GBP – 31 Euro EUR – 91 US Dollar USD – 1 UAE Dirham AED

    • Nithya Vasudevan

      Did you mean online? Because this project reads offline XML only. If you are looking to fetch XML from online refer this link.

  • venugopal

    No, this is offline online only but my data is following


    Office Maintenance

    British Pounds


    US Dollar

    This is my data i want to fetch into two spinners using sax parsing please help me in codeing right now i am doing in offline only that is keeping the file in assests folder and fetching its urgent please help me….

  • sachin

    yo project na chaale…

    • Ankit

      exactly…koni chalda.

      • sachin

        kati sahi bolen laagra h bhai…..

  • Michael

    Thanks, helped

  • Marian

    Great tutorial! Helped me a lot. But how exactly can i change the code to load the xml-file from sd-card?

  • Pingback: Error While Parsing XML file Using Xml DOMParser : Android : Android Community - For Application Development

  • Prakash

    Followed one of your tutorials and it worked. But when I added that to my existing code inside another activity it does not work. Would you be willing to help me

    • Nithya Vasudevan

      What kind of error you are getting and what are you trying to do?

      • Prakash

        Hi Nithya
        Thanks so much for replying. I have followed few of your tutorials and learnt alot in android.

        I have used this code and it works if I use the toast. But I am trying to list the details underneath the spinner rather than a toast. But it would not like list adapter or text view/list view….
        How could I display the details in multi line list view from the spinner select.
        Much appreciated if you could help

  • Pingback: Android webservice client: How data extract data from xml file : Android Community - For Application Development

  • Anil

    Hey thank you for this great example. Now, I want to add new elements in root tag. For that I need to create Class, that I know, but I am new to it. Can you help me to solve this? I have to write this class to write in existing XML file. Take your example. Suppose I have added new details such as new id, name, department etc from GUI, those data should be added to employees.xml and when i click on button, all data should be there in spinner.
    Thank you…

  • mrunalini

    Hey i am getting an error “R cannot be resolved to a variable”..What should i do?

  • falahgs

    Thanks for help

    how can i read xml file from sd card offline ….?
    by this sax parser ,,,would u plz help me …?

    Thanks again so much

  • tanay tandon

    great tutorial but can you please explain the exact purpose of
    Employee employee = (Employee) parent.getItemAtPosition(pos);
    thanks in advance

  • Jack


    I get similar errors. Maybe there are differences in android software versions (I use the latest onec of Android and Eclipse). Any help is welcome. The errors:
    - Error: No resource found that matches the given name (at ‘style’ with value ‘@style/spinner’). It happens in list_item.xml
    - Invalid start tag LinearLayout. It happens in styles.xml
    - R cannot be resolved to a variable. It happens in SAXParserActivity.

    So, there is no way to compile and run.

  • mahak

    please provide the source code also

  • Wayne

    Great tutorial, just needed to change the package names and move the </email> to before the and it works and even added extra data to the xml file manually.

    this comes to my next question.

    1. How do I write from the app new employee data. ( some kind of input edit page, with edit text, then write to employees.xml ?

    2. I would also like to select the xml file used, as the data I have is fixed(for another app), but I might want to add a file with the new data on.

    for example.

    I have a list of commands for a system,

    lets say system1.xml id1: name of system 1 (instead of ID and employee name)

    then another file system2.xml id2: name of system 2 (instead of ID and employee name)

    the data in the files will be for a list of say 20+ commands, the xml file will have:-







  • Pingback: Android: Simple XML SAX Parser – Displays Same Data Over and Over |

  • Zhuinden

    characters method should use StringBuilder instead of new String()