Android XML Parser – XMLPullParser

Filed Under: Android

Welcome to android xml parser example using XMLPullParser. We will have a sample XML file that we will parse in android app and display it on the page.

Android XML Parser

XML stands for Extensible Mark-up Language. XML files are commonly parsed in android to retrieve the relevant information from them. There are three types of android XML parser that we can use.

  1. SAX Parsers
  2. DOM Parsers
  3. XMLPullParser

DOM Parser : DOM parser use an object based approach where the whole xml is loaded into the memory and validated. Then it starts parsing the xml document. It parses from the starting node to the end node. Particular nodes cannot be parsed. Overall it’s slower than the other two.

SAX and XMLPullParser : These use an object based approach and are similar in terms of memory and performance. SAX is similar to DOM in the context that it begins parsing from top to bottom and there is no way to parse only particular nodes. On the contrary, XMLPullParser can parse particular nodes.

An XML file consists of 4 major components.

  1. Prolog : The first line that contains the information about a file is prolog. Typically this is the line:
  2. Events : Events in an XML file include simple start and end tags and more
  3. Text : It’s simple text in between two tags. Example: My Text</RandomTag
  4. Attributes : Attributes are the additional properties of a tag that are present within the tag. Example : Some Text or nested tags

XMLPullParser

XMLPullParser is the recommended android xml parser.

In this tutorial we’ll look to implement an XMLPullParser in our android application.

Android XML Parser Example Project Structure

android xml parser

Android XML Parser code

We’ve created a assets directory inside the main directory and added an xml file there as shown below.


<?xml version="1.0" encoding="utf-8"?>
<countries>
    <country id="1">
        <name>
            India
        </name>
        <capital>
            New Delhi
        </capital>
    </country>

    <country id="2">
        <name>
            Australia
        </name>
        <capital>
            Canberra
        </capital>
    </country>

    <country id="3">
        <name>
            USA
        </name>
        <capital>
            Washington, D.C.
        </capital>
    </country>

</countries>

Note: The “id” is the attribute.

The MainActivity.java is given below:


package com.journaldev.xmlparsing;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView= (TextView)findViewById(R.id.text);

        XmlPullParserFactory pullParserFactory;

        try {
            pullParserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = pullParserFactory.newPullParser();

            InputStream in_s = getApplicationContext().getAssets().open("sample.xml");
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(in_s, null);

            ArrayList<Country> countries=  parseXML(parser);

            String text="";

            for(Country country:countries)
            {

                text+= "id : "+country.getId()+" name : "+country.getName()+" capital : "+country.getCapital()+"\n";
            }

            textView.setText(text);



        } catch (XmlPullParserException e) {

            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private ArrayList<Country> parseXML(XmlPullParser parser) throws XmlPullParserException,IOException
    {
        ArrayList<Country> countries = null;
        int eventType = parser.getEventType();
        Country country = null;

        while (eventType != XmlPullParser.END_DOCUMENT){
            String name;
            switch (eventType){
                case XmlPullParser.START_DOCUMENT:
                    countries = new ArrayList();
                    break;
                case XmlPullParser.START_TAG:
                    name = parser.getName();
                    if (name.equals("country")){
                        country = new Country();
                        country.id=parser.getAttributeValue(null,"id");
                    } else if (country != null){
                        if (name.equals("name")){
                            country.name = parser.nextText();
                        } else if (name.equals("capital")){
                            country.capital = parser.nextText();
                        }
                    }
                    break;
                case XmlPullParser.END_TAG:
                    name = parser.getName();
                    if (name.equalsIgnoreCase("country") && country != null){
                        countries.add(country);
                    }
                    }
            eventType = parser.next();
        }

        return countries;

        }
}

XMLPullParser instantiation

XMLPullParser can be instantiated in two ways.

  1. 
    XmlPullParserFactory pullParserFactory;
    		try {
    			pullParserFactory = XmlPullParserFactory.newInstance();
    			XmlPullParser parser = pullParserFactory.newPullParser();
    		} catch (XmlPullParserException e) {
    
    			e.printStackTrace();
    		}
    
  2. 
    XmlPullParser parser = Xml.newPullParser();
    

    Using switch statements and while loops we parse every tag and look for the relevant data and add the whole object to the ArrayList when the tag ends. We’ve just iterated through the complete ArrayList and appended the strings to display in the default TextView that’s present.

    The output of the application is given below.
    android xml parser, XMLPullParser Example

    This brings an end to android xml parser tutorial. You can download the Android XML Parsing using XMLPullParser Project from the link given below.

    Reference: Android Official Doc

Comments

  1. Martin Vysny says:

    The article uses the “official approach” as suggested by Google, which is simply ridiculously complicated. You can try out https://gitlab.com/mvysny/konsume-xml for a much simpler approach.

  2. Victor Magana says:

    Very helpful example, it took me a while to understand since its my first time with Java xml library. Once it understood how it was walking the xml tree it made sense. Thanks for the help.

  3. Prashant Kumar says:

    This is very helpful but i am still wondering,how can i set this in list view??

  4. Harikrishna says:

    In above, The values are displayed in textview and how can we display those values in recycler view? pls help me harikrishna.nallani@gmail.com

    1. N Basavaraj Patil says:

      yes u can display,justpass the arraylist to recycler view adapter

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages