articles

Home / DeveloperSection / Articles / XmlPullParser in Android

XmlPullParser in Android

Manoj Pandey4677 18-Feb-2015

Previously, we learn about SAX parser in Android. Now we see how to use XmlPullParser in Android.

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.

Android recommends to use XmlPullParser to parse the xml file than SAX and DOM because it is fast.

The org.xmlpull.v1.XmlPullParser interface provides the functionality to parse the XML document using XmlPullParser.

1. Create an Android Project

2. Add xml file inside assets folder and add following code

 

<?xml version="1.0" encoding="UTF-8"?>

<employees>

    <employee>

        <id>1</id>

        <name>Adney</name>

        <salary>50000</salary>     

    </employee>

    <employee>

        <id>2</id>

        <name>Kaarle</name>

        <salary>60000</salary> 

    </employee>

     <employee>

        <id>3</id>

        <name>Mike</name>

        <salary>60000</salary> 

    </employee>

</employees>

 

3. Add listview in activity_main.xml 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity" >

 

    <ListView

        android:id="@+id/listView1"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" >

    </ListView>

 

</RelativeLayout>

 Add been class as name Employee

package com.example.xmlpullparsing;

 

// Been class of list

public class Employee {

     private int id;

     private String name;

     private String salary;

 

     public int getId() {

           return id;

     }

 

     public void setId(int id) {

           this.id = id;

     }

 

     public String getName() {

           return name;

     }

 

     public void setName(String name) {

           this.name = name;

     }

 

     public String getSalary() {

           return salary;

     }

 

     public void setSalary(String salary) {

           this.salary = salary;

     }

 

     @Override

     public String toString() {

           return "\n Name= " + name + "\n Salary= " + salary;

     }

}

 

Create XmlPullParserHandler class which parse data from xml file

package com.example.xmlpullparsing;

 

import java.io.IOException;

import java.io.InputStream;

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 {

     private List<Employee> employees = new ArrayList<Employee>();

     private Employee employee;

     private String text;

 

     public List<Employee> getEmployees() {

           return employees;

     }

 

     public List<Employee> parse(InputStream is) {

           try {

                // XmlPullParserFactory class is used to create implementations of

                // XML Pull Parser defined in XMPULL V1 API.

                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();

                // setNamespaceAware specifies that the parser produced by this

                // factory will provide

                // support for XML namespaces.

                factory.setNamespaceAware(true);

                // Creates a new instance of a XML Pull Parser using the currently

                // configured factory features.

                XmlPullParser 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();

                           }

                           break;

 

                     case XmlPullParser.TEXT:

                           text = parser.getText();

                           break;

 

                     case XmlPullParser.END_TAG:

                           if (tagname.equalsIgnoreCase("employee")) {

                                // add employee object to list

                                employees.add(employee);

                           } else if (tagname.equalsIgnoreCase("id")) {

                                employee.setId(Integer.parseInt(text));

                           } else if (tagname.equalsIgnoreCase("name")) {

                                employee.setName(text);

                           } else if (tagname.equalsIgnoreCase("salary")) {

                                employee.setSalary(text);

                           }

                           break;

 

                     default:

                           break;

                     }

                     eventType = parser.next();

                }

 

           } catch (XmlPullParserException e) {

                e.printStackTrace();

           } catch (IOException e) {

                e.printStackTrace();

           }

 

           return employees;

     }

}

 

Now add following code in MainActivity.class

  

package com.example.xmlpullparsing;

 

import java.io.IOException;

import java.io.InputStream;

import java.util.List;

 

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.widget.ArrayAdapter;

import android.widget.ListView;

 

public class MainActivity extends Activity {

 

     @Override

     protected void onCreate(Bundle savedInstanceState) {

          super.onCreate(savedInstanceState);

          setContentView(R.layout.activity_main);

          // find data from xml layout

          ListView listView = (ListView) findViewById(R.id.listView1);

 

          List<Employee> employees = null;

          try {

              XmlPullParserHandler parser = new XmlPullParserHandler();

              // A readable source of bytes.

              InputStream is = getAssets().open("employees.xml");

              employees = parser.parse(is);

               // bind data in adapter

              ArrayAdapter<Employee> adapter = new ArrayAdapter<Employee>(this,

                        android.R.layout.simple_list_item_1, employees);

              // set adapter in listview

              listView.setAdapter(adapter);

 

          } catch (IOException e) {

 

          }

 

     }

 

     @Override

     public boolean onCreateOptionsMenu(Menu menu) {

          // Inflate the menu; this adds items to the action bar if it is present.

          getMenuInflater().inflate(R.menu.activity_main, menu);

          return true;

     }

 

}

 

Now run your application


XmlPullParser in Android


Updated 07-Sep-2019

Leave Comment

Comments

Liked By