Android XMLPullParser

| Page Views: 87

Android XMLPullParser Tutorial and Examples.

What is XMLPullParser

XML Pull Parser is an interface that defines parsing functionality provided in XMLPULL V1 API.

public interface XmlPullParser

XMLPullParser resides in the org.xmlpull.v1 package.

XmlPullParser is an android specific API is not found in standard Java. However it has similarities to the Stax parser.

For Java you can use SAX, DOM and Stax Parsers. However these have their own limitations with regards to performance that's why Android Engineers chose XmlPullParser, which does consume less memory.

Two of the most important methods in XmlPullParser include:

  1. next() : - provides access to high level parsing events.
  2. nextToken() - allows access to lower level tokens.

The current event state of the parser can be determined by calling the getEventType() method. Initially, the parser is in theSTART_DOCUMENT state.

The methodnext() advances the parser to the next event. The int value returned from next determines the current parser state and is identical to the value returned from following calls to getEventType ().

Th following event types are seen by next():

START_TAG : An XML start tag was read. TEXT : Text content was read; the text content can be retrieved using thegetText() method. (when in validating mode next() will not report ignorable whitespace, use nextToken() instead) END_TAG : An end tag was read END_DOCUMENT : No more events are available

Here's a simple example:

import java.io.IOException;
 import java.io.StringReader;

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

 public class SimpleXmlPullApp
 {

     public static void main (String args[])
         throws XmlPullParserException, IOException
     {
         XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
         factory.setNamespaceAware(true);
         XmlPullParser xpp = factory.newPullParser();

         xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) );
         int eventType = xpp.getEventType();
         while (eventType != XmlPullParser.END_DOCUMENT) {
          if(eventType == XmlPullParser.START_DOCUMENT) {
              System.out.println("Start document");
          } else if(eventType == XmlPullParser.START_TAG) {
              System.out.println("Start tag "+xpp.getName());
          } else if(eventType == XmlPullParser.END_TAG) {
              System.out.println("End tag "+xpp.getName());
          } else if(eventType == XmlPullParser.TEXT) {
              System.out.println("Text "+xpp.getText());
          }
          eventType = xpp.next();
         }
         System.out.println("End document");
     }
 }

The above example will generate the following output:

 Start document
 Start tag foo
 Text Hello World!
 End tag foo
 End document

Quick Examples

(a). How to Read RSS Items into an ArrayList From a Stream via XmlPullParser

First you initialize the ArrayList to hold the RSS items. Then create the XmlPullParser:

XmlPullParser parser = Xml.newPullParser();

In this case our input is a StringReader. Then we invoke our nextTag(). Then read and analyze our feed.

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.Xml;

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

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

class RssParser {

    private static final String TAG = "RssParser";

    private static final String TAG_TITLE = "title";
    private static final String TAG_LINK = "link";
    private static final String TAG_ENCLOSURE = "enclosure";
    private static final String TAG_RSS = "rss";
    private static final String TAG_ITEM = "item";

    @NonNull
    ArrayList<RssItem> parse(String stream) {
        ArrayList<RssItem> items = null;
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(new StringReader(stream));
            parser.nextTag();
            parser.require(XmlPullParser.START_TAG, null, TAG_RSS);
            items = readFeed(parser);
        } catch (@NonNull XmlPullParserException | IOException e) {
            Log.w(e.getMessage(), e);
        } finally {
            if (items == null) {
                items = new ArrayList<>();
            }
        }
        return items;
    }

    /**
     * Read and analyze RSS feed.
     *
     * @param parser the XML parser with some objects to be classified
     * @return a list of well formed news that can be clicked later inside {@link org.mbach.lemonde.article.ArticleActivity}
     */
    @NonNull
    private ArrayList<RssItem> readFeed(@NonNull XmlPullParser parser) {
        ArrayList<RssItem> items = new ArrayList<>();
        RssItem item = new RssItem();
        String text = null;
        /// TODO: store cache calls maybe here!
        try {
            while (parser.next() != XmlPullParser.END_DOCUMENT) {

                String tagName = parser.getName();
                switch (parser.getEventType()) {
                    case XmlPullParser.START_TAG:
                        if (tagName.equalsIgnoreCase(TAG_ITEM)) {
                            item = new RssItem();
                        }
                        break;
                    case XmlPullParser.TEXT:
                        text = parser.getText();
                        break;
                    case XmlPullParser.END_TAG:
                        if (tagName.equalsIgnoreCase("item")) {
                            items.add(item);
                        } else if (tagName.equalsIgnoreCase(TAG_LINK)) {
                            item.setLink(text);
                        } else if (tagName.equalsIgnoreCase(TAG_TITLE)) {
                            item.setTitle(text);
                        } else if (tagName.equalsIgnoreCase(TAG_ENCLOSURE)) {
                            text = parser.getAttributeValue(null, "url");
                            item.setEnclosure(text);
                        }
                        break;
                    default:
                        break;
                }
            }
        } catch (XmlPullParserException | IOException e ) {
            Log.e(TAG, "The stream cannot be parsed! Is it really well-formed? " + e.getMessage());
        }
        return items;
    }
}
(b). How to Read User Identities Settings From XML File.

Say you have stored user settings in an xml file. You can load them via XmlPullParser:

private static List<ImportedIdentity> parseIdentities(XmlPullParser xpp)
        throws XmlPullParserException, IOException {
    List<ImportedIdentity> identities = null;

    int eventType = xpp.next();
    while (!(eventType == XmlPullParser.END_TAG && SettingsExporter.IDENTITIES_ELEMENT.equals(xpp.getName()))) {
        if (eventType == XmlPullParser.START_TAG) {
            String element = xpp.getName();
            if (SettingsExporter.IDENTITY_ELEMENT.equals(element)) {
                if (identities == null) {
                    identities = new ArrayList<>();
                }

                ImportedIdentity identity = parseIdentity(xpp);
                identities.add(identity);
            } else {
                Timber.w("Unexpected start tag: %s", xpp.getName());
            }
        }
        eventType = xpp.next();
    }

    return identities;
}

Top Android XMLPullParser Full Examples

Let's look at some examples.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.




Recommendations


What do You Think


Previous Post Next Post