Android: Simple XMLPullParser Tutorial

21 December 2012 By Nithya Vasudevan 63,194 views 18 Comments
32 Flares Twitter 0 Facebook 19 Google+ 13 32 Flares ×

There are three types of Android XML parsers – DOM, SAX and XmlPullParser. You can use DOM and SAX parser API which are provided by Java platform. In addition to these two parsers, Android provides XmlPullParser which is similar to StAX parser and is also the recommended XML parsing in Android. This Android XML parsing example explains how to parse a simple XML using Android XMLPullParser.

Project Description

  • This Android 4 XmlPullParser example shows how to parse a simple XML containing employee details and display the result in ListView.
  • This example stores XML file in project’s assets folder and opens the file as InputStream using AssetManager.
  • When the main activity is loaded, it parses the XML and displays the employee details in ListView.

Environment Used

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


Create Android Project

  • Create a new Android Project and enter the Application name as SimpleXMLPullParser.
  • Project name as SimpleXMLPullParser.
  • Enter the package name as com.theopentutorials.xml.activities.
  • Enter the Activity name as XMLPullParserActivity.
  • Enter the Layout name as main.
  • 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/strings.xml and replace it with following content.

<?xml version="1.0" encoding="utf-8"?>
    <string name="app_name">SimpleXMLPullParser</string>
    <string name="hello_world">Simple XMLPullParser Activity</string>
    <string name="menu_settings">Settings</string>

XML layout files

main layout file (main.xml)

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

<RelativeLayout xmlns:android=""
    tools:context=".XMLPullParserActivity" >

        android:textSize="16sp" />

        android:layout_below="@id/text" />


ListView item layout file (list_item.xml)

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android=""
    android:textSize="16sp" />

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 + "\n" + department + "-" + type
				+ "\n" + email;

Create XMLPullParserHandler class

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


import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;


public class XMLPullParserHandler {
	List<Employee> employees;
	private Employee employee;
	private String text;

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

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

	public List<Employee> parse(InputStream is) {
		XmlPullParserFactory factory = null;
		XmlPullParser parser = null;
		try {
			factory = XmlPullParserFactory.newInstance();
			parser = factory.newPullParser();

			parser.setInput(is, null);

			int eventType = parser.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {
				String tagname = parser.getName();
				switch (eventType) {
				case XmlPullParser.START_TAG:
					if (tagname.equalsIgnoreCase("employee")) {
						// create a new instance of employee
						employee = new Employee();

				case XmlPullParser.TEXT:
					text = parser.getText();

				case XmlPullParser.END_TAG:
					if (tagname.equalsIgnoreCase("employee")) {
						// add employee object to list
					} else if (tagname.equalsIgnoreCase("name")) {
					} else if (tagname.equalsIgnoreCase("id")) {
					} else if (tagname.equalsIgnoreCase("department")) {
					} else if (tagname.equalsIgnoreCase("email")) {
					} else if (tagname.equalsIgnoreCase("type")) {

				eventType =;

		} catch (XmlPullParserException e) {
		} catch (IOException e) {

		return employees;

XML Pull Parser is an interface that defines parsing functionality provided in XMLPULL V1 API. This is a simple interface – parser consists of one interface, one exception and one factory to create parser.

Steps required to parse a XML using XML pull parser are,

  • get instance of XMLPULL facotry as shown in line 30
  • (optional step) by default factory will produce parsers that are not namespace aware; to change setNamespaceAware() function must be called as shown in line 31
  • create an instance of the parser as shown in line 32
  • Then set parser input as shown in line 34
  • and now start parsing. Typical XMLPULL applicaition will repeatedly call next() function (line 71) to retrieve next event, process event until the event is END_DOCUMENT.

Create XMLPullParserActivity class

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


import java.util.List;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class XMLPullParserActivity extends Activity {

	ListView listView;
	protected void onCreate(Bundle savedInstanceState) {
		listView = (ListView) findViewById(;
		List<Employee> employees = null;
		try {
			XMLPullParserHandler parser = new XMLPullParserHandler();
			employees = parser.parse(getAssets().open("employees.xml"));
			ArrayAdapter<Employee> adapter = 
				new ArrayAdapter<Employee>(this,R.layout.list_item, employees);
		} catch (IOException e) {

	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(, menu);
		return true;



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    android:versionName="1.0" >

        android:targetSdkVersion="16" />

        android:theme="@style/AppTheme" >
            android:label="@string/app_name" >
                <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: , , , , , , , ,

  • Pingback: Android Pull Parser from url.xml | BlogoSfera

  • Kari Labermo

    Hi Nithya Vasudevan

    First of all thanks for a very good tutorial. I almost understand the cod. I’m very new to this type of programing. Here is my questions and i hope you can find time to answer me.

    If i understand all correct this bit of code is to open the employees.xml from assets.

    employees = parser.parse(getAssets().open(“employees.xml”));

    1: But if i like say to open the file from the external or internal SDCARD let say /sdcard/datafile.xml how is this done?

    2: If i like to open the file direct from a http adress how is this done?

    Best regards
    Kari Labermo

    • Nithya Vasudevan

      Please take a look at this link which explains how to parse a XML from http using SAX parser

      You can apply the same logic to XMLPullParser.

      • BP

        I am having a similar issue, for example the line 27 in your class pulls the data from the XML, that I understand.What I would appreciate, is what changes would you need to make as to implement the http route, what’s the simplest solution without deviating from your example?

  • Mat Garreau

    Very useful tutorial that help me a lot. Thank you Nithya :-)

  • theAydinator


    Do you can publish the same tutorial just with a custom adapter please?

    Thank you

  • Abdessamad Idrissi

    thanks for the tutorial.
    just to note that the email in the XML must be rechecked by deleting the extra data:

    /* */

    • chha

      thank u soo much :)

  • rahul

    Helpful tutorial.

  • Henric Carlsson

    Theanks for the tutorial, it’s exactly what I need. I have a problem in the where main cannot be found in:

    getMenuInflater().inflate(, menu);

    I guess that suggests that the java files package cannot direct the code to the main package of some reason. Any idea why?

    • Henric Carlsson

      I have made a project clean up but it did not help the issue.

  • Pingback: Parsing local xml android with drawable

  • prabhakar

    It is a useful tutorial , I don’t understand how to implement for the login activity.
    thanks in advance.

  • hoanganh25991

    Thank you for the tutorial.

  • Vaibhav Srivastav

    Thanks it’s nice tutorial……for beginners

  • Junaid Pahat

    if i want to parse link(rss) what should i do where to add url in above code

  • RT Imraj

    thanks for the tutorial . i did this parsing data inside my mainactivity. i don’t know how to search a item using filter . here is my problem. can you please solve the issue or help to guide ?

  • Jack Pickering

    How do you get around the error ‘Symbol R not recognised’ in the XMLPullParserActivity class?
    Thanks, Jack