XML Processing in Android and Java: XmlPull Example

XmlPull example in Java or Android.

1 What is XmlPull

XmlPull is another way to parse XML document besides DOM and SAX.

In fact, XmlPull works like SAX in some respects.

  • XmlPull needn't create a DOM tree in memory, either.
  • XmlPull will also read the XML document as a stream and do parsing work once the XML node token in the stream is recognized.

how_xmlpull_works

On the other hand, there are important differences between XmlPull and SAX.

  • SAX parser need a events handler; XmlPull parser will handle the events itself.
  • SAX can only receive the events passively; XmlPull will process the events on his own initiative.
  • SAX cann't stop the course of parsing once you start; XmlPull will take full control of parsing "cursor" and can quit the parsing conveniently.

Video illustration of how XmlPull works.

2 Install

For Java application, you can download XmlPull implementation library from xmlpull.org. kXML is recommended.

After downloading the jar library file, paste it to your project and then add it to build path of your project.

add_xmlpull_jar_lib

Android has already provided XmlPull API implementation which is located in package org.xmlpull.v1.*.

3 Example codes

XmlPull example project.

xmlpull_example_project

3.1 Sample XML

Given a sample XML file.

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book ISBN="ISBN-001">
        <name>How To Be A Cat</name>
        <author>Tom</author>
        <price>$29</price>
    </book>
    <book ISBN="ISBN-002">
        <name>How To Be A Mouse</name>
        <author>Jerry</author>
        <price>$25</price>
    </book>
</books>

3.2 JavaBean

JavaBean class for book item in BookBean.java.

package xmlpulldemo;

public class BookBean {
    private String name;
    private String author;
    private String price;
    private String ISBN;
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getAuthor() {
        return author;
    }
    
    public void setAuthor(String author) {
        this.author = author;
    }
    
    public String getPrice() {
        return price;
    }
    
    public void setPrice(String price) {
        this.price = price;
    }
    
    public String getISBN() {
        return ISBN;
    }
    
    public void setISBN(String iSBN) {
        ISBN = iSBN;
    }
    
    @Override
    public String toString() {
        return "[" + this.name + "]" + " by " + this.author + " at " + this.price;
    }
}

3.3 Parsing XML using XmlPull

package xmlpulldemo;

import java.io.FileInputStream;
import java.util.ArrayList;

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

public class XmlPullDemo {

    public static void main(String[] args) {
    
        BookBean book = null;
        ArrayList<BookBean> bookList = null;
        
        try {
            // Initialize XmlPullParser
            XmlPullParserFactory xppFactory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = xppFactory.newPullParser();
            xmlPullParser.setInput(new FileInputStream("src/Books.xml"), "utf-8"); 
            
            int eventType = xmlPullParser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        if ("books".equals(xmlPullParser.getName())) {
                            bookList = new ArrayList<BookBean>();
                        }
                        
                        if ("book".equals(xmlPullParser.getName())) {
                            book = new BookBean();
                            book.setISBN(xmlPullParser.getAttributeValue(XmlPullParser.NO_NAMESPACE, "ISBN"));
                        }
                        
                        if ("name".equals(xmlPullParser.getName())) {
                            String name = xmlPullParser.nextText();
                            book.setName(name);
                        }
                        
                        if ("author".equals(xmlPullParser.getName())) {
                            String author = xmlPullParser.nextText();
                            book.setAuthor(author);
                        }
                        
                        if ("price".equals(xmlPullParser.getName())) {
                            String price = xmlPullParser.nextText();
                            book.setPrice(price);
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if ("book".equals(xmlPullParser.getName())) {
                            bookList.add(book);
                        }
                        break;
                    default:
                        break;
                } // end switch
                
                // Move forward the parsing "cursor", or you can stop parsing
                eventType = xmlPullParser.next();
                
            } // end whiles

            if (bookList != null) {
                for (BookBean bb : bookList) {
                    System.out.println(bb);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

If you are using XmlPull in Android application, you should initialize your XmlPullParser as follows.

InputStream is = getClass().getClassLoader().getResourceAsStream("assets/Books.xml");
// Or
// InputStream is = getResources().getAssets().open("Books.xml");

XmlPullParser xmlPullParser = Xml.newPullParser();
xmlPullParser.setInput(is, "utf-8");

Comments