Home Tutorials Training Consulting Books Company Contact us


Get more...

XML processing with Android. This article describes how to process XML with Android.

1. XML processing in Android

The Java programming language provides several standard libraries for processing XML files.

Per default, Android provides for XML parsing and writing the XmlPullParser class. This parser is not available in standard Java but is similar to the Stax parser. The parser is hosted at http://www.xmlpull.org/.

On Android you use either the XmlPullParser or an additioal library like Simple which makes XML parsing easier.

The SAX and the DOM XML parsers are available on Android. SAX and DOM have their limitations, therefore it is not recommended to use them on Android. Therefore this tutorial does not give an example for the usage of this library.

The Java standard provides also the Stax parser. This parser is not part of the Android platform.

2. Example for using XmlPullParser

The Javadoc of XmlPullParser gives a nice example how you can use this library.

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

 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException.html;
 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.END_DOCUMENT) {
              System.out.println("End 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();
         }
     }
 }

3. Prerequisites for the following exercise

This exercise is based on the Android library project example.

4. Exercise: Parsing an RSS feed with the XML pull parser

In this exercise you download RSS feed data from the network using your com.example.android.rssfeedlibary project.

4.1. Add permission to access the Internet

Add the permission to use the Internet to the Android manifest file of your RSS Reader project.

<uses-permission android:name="android.permission.INTERNET"/>

Ensure that you added the permission to the correct manifest file. If you add this permission to the library project, Internet access will not work.

The resulting manifest should look similar to the following listing.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.rssfeed"
    android:versionCode="1"
    android:versionName="1.1" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name="RssApplication"
        android:allowBackup="false"
        android:icon="@drawable/launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="RssfeedActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

4.2. Perform network access

Change the parse method in RssFeedProvider so that it reads the RSS feed. Also writes the output to the Android log.

package com.example.android.rssfeedlibrary;

import android.util.Log;
import android.util.Xml;

import org.xmlpull.v1.XmlPullParser;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RssFeedProvider {

    static final String PUB_DATE = "pubDate";
    static final String DESCRIPTION = "description";
    static final String CHANNEL = "channel";
    static final String LINK = "link";
    static final String TITLE = "title";
    static final String ITEM = "item";



    public static List<RssItem> parse(String rssFeed) {
        List<RssItem> list = new ArrayList<RssItem>();
        XmlPullParser parser = Xml.newPullParser();
        InputStream stream = null;
        try {
            // auto-detect the encoding from the stream
            stream = new URL(rssFeed).openConnection().getInputStream();
            parser.setInput(stream, null);
            int eventType = parser.getEventType();
            boolean done = false;
            RssItem item = null;
            while (eventType != XmlPullParser.END_DOCUMENT && !done) {
                String name = null;
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        name = parser.getName();
                        if (name.equalsIgnoreCase(ITEM)) {
                            Log.i("new item", "Create new item");
                            item = new RssItem();
                        } else if (item != null) {
                            if (name.equalsIgnoreCase(LINK)) {
                                Log.i("Attribute", "setLink");
                                item.setLink(parser.nextText());
                            } else if (name.equalsIgnoreCase(DESCRIPTION)) {
                                Log.i("Attribute", "description");
                                item.setDescription(parser.nextText().trim());
                            } else if (name.equalsIgnoreCase(PUB_DATE)) {
                                Log.i("Attribute", "date");
                                item.setPubDate(parser.nextText());
                            } else if (name.equalsIgnoreCase(TITLE)) {
                                Log.i("Attribute", "title");
                                item.setTitle(parser.nextText().trim());
                            }
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        name = parser.getName();
                        Log.i("End tag", name);
                        if (name.equalsIgnoreCase(ITEM) && item != null) {
                            Log.i("Added", item.toString());
                            list.add(item);
                        } else if (name.equalsIgnoreCase(CHANNEL)) {
                            done = true;
                        }
                        break;
                }
                eventType = parser.next();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }
}

4.3. Validate

Start your application and load the RSS feed data.

Once the RSS feed is processed, the RssItems should be visible in the list fragment.