Create and parse XML on the Android 3.0 platform

Use the same build, parser, and transformer APIs for XML and Android

Android, the most commonly used smartphone platform, also functions on mobile tablets. XML is the standard medium of data exchange. You can use the same builder, parser, and transformer APIs for standard XML parsing and transformation and for Android. With the javax.xml.parsers.DocumentBuilder, you can create an org.w3c.dom.Document object. In this article, create and parse an XML document on an Android device using a DocumentBuilder object obtained from a DocumentBuilderFactory. You'll parse the XML document using an extension of an XML pull parser.

10 Apr 2012 - In response to reader comment about Listing 12 missing a line of code, the author requested the addition of this new line transformer.transform(domSource, result); immediately after this existing line: StreamResult result = new StreamResult(output).

Share:

Deepak Vohra, Consultant, Independent

Deepak Vohra is a Sun Certified Java programmer, and Sun Certified Web Component Developer. Deepak has published in Java Developer's Journal and XML Journal.



10 April 2012 (First published 18 October 2011)

Also available in Chinese Russian Japanese Vietnamese

Introduction

Android, the most commonly used smartphone platform, works on both smartphones and mobile tablets. Motorola XOOM is an Android Tablet. In this article, learn to create and parse an XML document on an Android device. For outputting XML, you can use the standard javax.xml.transform.Transformer class. To parse XML on Android, you can use the DOM and SAX parsers. The org.xmlpull.v1.XmlPullParser pull parser is also an option for parsing XML. The examples in this article use the Android Platform 3.0 for processing XML.

Download the example application used in this article.


Setting up the environment

To follow along with the examples in this article, install and configure the following software See Resources for links.

Frequently used abbreviations

  • ADT: Android Development Tools
  • API: Application programming interface
  • AVD: Android Virtual Device
  • DOM: Document object model
  • IDE: Integrated Development Environment
  • JSON: JavaScript Object Notation
  • SAX: Simple API for XML
  • SDK: Software Development Kit
  • UI: User Interface
  • XML: Extensible Markup Language
  1. Install the Eclipse IDE.
  2. Install the Android Development Tools (ADT) plug-in for Eclipse, which provides a set of extensions to develop Android applications in Eclipse.
  3. Download and install the Android SDK Platform, which provides tools for developing Android applications.
  4. Select Window > Android SDK, and AVD Manager, to launch the Android SDK and AVD Manager in Eclipse.
  5. Create an Android Virtual Device (AVD), which is an emulator for Android, in the Android SDK and AVD Manager.

    Select Platform 3.0 and API 11 for the AVD.

Creating an XML document

In this section, you create an XML document on Android. The first step is to create an Android project.

  1. In the Eclipse IDE, select File > New. In the New dialog, select Android > Android Project. Click Next.
  2. In the New Android Project window, as in Figure 1, specify:
    • Project name: CreatingXML
    • Build Target check box: Android Platform 3.0 and API 11
    • Properties:
      • Application name: CreatingXML
      • Package name: android.xml
      • Select Create Activity: Activity class (CreatingXML). An activity represents a user interaction. The class extending the Activity class creates a window for a UI.
      • Minimum SDK Version: 11
    Figure 1. Create an Android project for platform 3.0
    Screen capture of how to create an Android project for platform 3.0
  3. Click Next.
  4. Click Finish. An Android project that you'll use to create an XML document is created. The Android project consists of these files:
    • An activity class, CreatingXML, which extends the Activity class.
    • The res/layout/main.xml file, which specifies the layout of the Android UI components.
    • The AndroidManifest.xml file, which contains application configuration such as the package name, the main activity to launch when the Android application is started, application components, processes, permissions, and the minimum API level.

Figure 2 shows the directory structure of the Android project CreatingXML.

Figure 2. Android project to create an XML document
Screen capture of an Android project for creating an XML Document

In the res/layout/main.xml file, specify the layout of the Android UI components. Create a LinearLayout and set android:orientation to vertical. In this example, you'll display the XML document as a text message. Add a TextView element with id xmlresult to display the XML document, as in Listing 1.

Listing 1. Layout file, main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical" android:layout_width="fill_parent"
     android:layout_height="fill_parent">
     <TextView android:id="@+id/xmlresult" android:layout_width="fill_parent"
          android:layout_height="wrap_content" />
</LinearLayout>

In the AndroidManifest.xml file, specify the Activity to launch as CreatingXML. Specify the minimum Android version with the uses-sdk element 11. The activity, the intent-filter, and action are specified with the activity element and subelements. Listing 2 shows the file.

Listing 2. Configuration file, AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="android.xml"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="11" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".CreatingXML"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Now you'll create an XML document in the activity class CreatingXML, which extends the Activity class. Because the example uses the javax.xml.parsers.DocumentBuilder to create an XML document, import the following.

  • javax.xml.parsers.DocumentBuilder class
  • javax.xml.parsers.DocumentBuilderFactory class
  • org.w3c.dom package
  • javax.xml.transform.TransformerFactory class
  • javax.xml.transform.Transformer class
  • javax.xml.transform.dom.DOMSource class
  • javax.xml.transform.stream.StreamResult class

The onCreate(Bundle savedInstanceState) method is invoked when the activity starts. In the onCreate method, set the UI using the setContentView method and set the layout resource using setContentView(R.layout.main);.

Define the Android widget TextView object in the main.xml file using the findViewById method, with the id xmlresult, as follows: TextView xmlResult = (TextView) findViewById(R.id.xmlresult); .

Create an instance of the DocumentBuilderFactory object using the static method newInstance(). Create a DocumentBuilder object using the newDocumentBuilder() method of the DocumentBuilderFactory class, as in Listing 3.

Listing 3. Create a DocumentBuilder
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

An XML document is represented by a DOM structure. Create a new Document object, using the newDocument() method of the DocumentBuilder class, with: Document document = documentBuilder.newDocument();.

Create the root element "catalog" of the Document object using the createElement() method: Element rootElement = document.createElement("catalog");.

As in Listing 4, set the publisher and journal attributes on the root element using the setAttribute method.

Listing 4. Set root Element attributes
rootElement.setAttribute("journal", "Oracle Magazine");
rootElement.setAttribute("publisher", "Oracle Publishing");

Append the root element to the Document object using the appendChild() method: document.appendChild(rootElement);.

Create an "article" element using the createElement() method. Append the element to the root element using the appendChild() method, as in Listing 5.

Listing 5. Create an "article" element
Element articleElement = document.createElement("article");
rootElement.appendChild(articleElement);

As in Listing 6, add an "edition" element to the "article" element.

Listing 6. Add "edition" element
Element editionElement = document.createElement("edition");
articleElement.appendChild(editionElement);

Add a text node to the "edition" element using the createTextNode() method. Set the text node value "Sept-Oct 2005" as follows: editionElement.appendChild(document.createTextNode("Sept-Oct 2005"));.

Similarly, create and add a "title" element to the "article" element. As in Listing 7, add a text node to the "title" element and set its value to "Creating Search Pages".

Listing 7. Create a text node
Element titleElement = document.createElement("title");
articleElement.appendChild(titleElement);
titleElement.appendChild(document.createTextNode("Creating Search Pages"));

Add an "author" element to the "article" element. Add a text node to the "author" element and set its value to "Steve Muench", as in Listing 8.

Listing 8. Add "author" element
authorElement = document.createElement("author");
articleElement.appendChild(authorElement);
authorElement.appendChild(document.createTextNode("Steve Muench"));

Add another "article" element to the root element. You can create an XML document DOM structure the same way you do for a non-Android application. The example will:

  • Output the DOM Document object to a ByteArrayOutputStream
  • Obtain the XML document as a string from the OutputStream
  • Set the string on the TextView widget on Android

Create a TransformerFactory object using the static method newInstance(). As in Listing 9, create a Transformer object using the newTransformer() method of the factory object.

Listing 9. Create a transformer object
TransformerFactory factory = TransformerFactory.newInstance();			
Transformer transformer = factory.newTransformer();

Create a java.util.Properties object and set the output properties for:

  • Indentation (INDENT)
  • Output format (METHOD)
  • The XML declaration (OMIT_XML_DECLARATION)
  • XML version (VERSION)
  • Encoding (ENCODING) of the XML document

To transform the DOM structure, you need a Source object and a Result object. Create a DOMSource object from the Document object. For the output, create a ByteArrayOutputStream and a StreamResult object from the ByteArrayOutputStream, as in Listing 10.

Listing 10. Transform the DOM structure
DOMSource domSource = new DOMSource(document.getDocumentElement());
OutputStream output = new ByteArrayOutputStream();
StreamResult result = new StreamResult(output);

Transform the Document object using the transform() method of the Transformer object, as follows: transformer.transform(domSource, result);.

Obtain the String object from the ByteArrayOutputStream object and set the String on the TextView widget xmlResult.

Listing 11. Get and set the String
String xmlString = output.toString();
xmlResult.setText(xmlString);

Listing 12 shows the Activity class CreatingXML.

Listing 12. Activity Class CreatingXML
package android.xml;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import java.util.Properties;
import javax.xml.transform.OutputKeys;

import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;

import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import javax.xml.transform.dom.DOMSource;

public class CreatingXML extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView     xmlResult = (TextView) findViewById(R.id.xmlresult);

        try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                      .newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory
                      .newDocumentBuilder();
            Document document = documentBuilder.newDocument();

            Element rootElement = document.createElement("catalog");
            rootElement.setAttribute("journal", "Oracle Magazine");
            rootElement.setAttribute("publisher", "Oracle Publishing");
            document.appendChild(rootElement);

            Element articleElement = document.createElement("article");
            rootElement.appendChild(articleElement);

            Element editionElement = document.createElement("edition");
            articleElement.appendChild(editionElement);
            editionElement.
            appendChild(document.createTextNode("Sept-Oct 2005"));

            Element titleElement = document.createElement("title");
            articleElement.appendChild(titleElement);
            titleElement.appendChild(document
                      .createTextNode("Creating Search Pages"));

            Element authorElement = document.createElement("author");
            articleElement.appendChild(authorElement);
            authorElement.
            appendChild(document.createTextNode("Steve Muench"));

            articleElement = document.createElement("article");
            rootElement.appendChild(articleElement);

            editionElement = document.createElement("edition");
            articleElement.appendChild(editionElement);
            editionElement.appendChild(document
                      .createTextNode("November - December 2010"));

            titleElement = document.createElement("title");
            articleElement.appendChild(titleElement);
            titleElement.appendChild(document
                      .createTextNode("Agile Enterprise Architecture"));

            authorElement = document.createElement("author");
            articleElement.appendChild(authorElement);
            authorElement.appendChild(document.createTextNode("Bob Rhubart"));

            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            Properties outFormat = new Properties();
            outFormat.setProperty(OutputKeys.INDENT, "yes");
            outFormat.setProperty(OutputKeys.METHOD, "xml");
            outFormat.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            outFormat.setProperty(OutputKeys.VERSION, "1.0");
            outFormat.setProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperties(outFormat);
            DOMSource domSource = 
            new DOMSource(document.getDocumentElement());
            OutputStream output = new ByteArrayOutputStream();
            StreamResult result = new StreamResult(output);
            transformer.transform(domSource, result);
            String xmlString = output.toString();
            xmlResult.setText(xmlString);

        } catch (ParserConfigurationException e) {
        } catch (TransformerConfigurationException e) {
        } catch (TransformerException e) {
        }

    }
}

At this point you can run the Android application. Right-click on the CreatingXML application node and select Run As > Android Application, as in Figure 3.

Figure 3. Run the Android application
Screen capture of how to run the Android application

The Android AVD starts and the Android application deploys on the AVD, as in Figure 4.

Figure 4. CreatingXML application installed on Android device
Screen capture of the CreatingXML application installed on Android device

Click the CreatingXML application icon. The application activity starts, and the XML document is created and displayed on the Android device, as in Figure 5.

Figure 5. Create and display an XML document on the Android device
Screen capture of creating and displaying an XML document on the Android device

Parsing an XML document

This section explains how to parse an XML document. You can use the standard DOM and SAX parsers or another parser. In the example, which uses the org.xmlpull.v1.XmlPullParser, you'll parse the XML document catalog.xml as in Listing 13.

Listing 13. catalog.xml
<?xml version = '1.0' encoding = 'UTF-8'?>
<catalog journal="Oracle Magazine" publisher="Oracle Publishing">
     <article>
          <edition>Sept-Oct 2005</edition>
          <title>Creating Search Pages</title>
          <author>Steve Muench</author>
     </article>
     <article>
          <edition>November - December 2010</edition>
          <title>Agile Enterprise Architecture</title>
          <author>Bob Rhubart</author>
     </article>
</catalog>

As in the previous section, Creating an XML document, you need to create an Android project for parsing the XML document.

  1. In the Eclipse IDE, select File > New. In the New dialog, select Android > Android Project. Click Next.
  2. In the New Android Project window, as in Figure 6, specify:
    • Project name: ParsingXML
    • Build Target check box: Android Platform 3.0 and API 11.
    • Properties:
      • Application name: ParsingXML
      • Package name: android.xml
      • Select Create Activity: Activity class (ParsingXML)
      • Minimum SDK version: 11
    Figure 6. Create an Android project for parsing an XML document
    Screen capture of how to create an Android project for parsing an XML document
  3. Click Finish.

    An Android project is created. It consists of:

    • An Activity class ParsingXML
    • A res/layout/main.xml file for layout
    • An AndroidManifest.xml file for application configuration

Parse the XML document and use labels to output the element values. The labels and element text node values are output to TextView widgets.

  1. In the main.xml file, add a TextView widget for each label and element text node value.
  2. Create a LinearLayout and set android:orientation to "vertical".
  3. Add the TextView elements with the following ids:
    • "journal_label"
    • "journal"
    • "publisher_label"
    • "publisher"
    • "edition1_label"
    • "edition1"
    • "title1_label"
    • "title1"
    • "author1_label"
    • "author1"
    • "edition2_label"
    • "title2_label"
    • "title2"
    • "author2_label"
    • "author2"

Listing 14 shows the main.xml file.

Listing 14. Layout file, main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical" android:layout_width="fill_parent"
     android:layout_height="fill_parent">
          <TextView android:id="@+id/journal_label"
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content"
               android:text="Journal:" />
          <TextView android:id="@+id/journal" android:singleLine="true"
               android:layout_width="fill_parent"
               android:layout_height="wrap_content" />
          <TextView android:id="@+id/publisher_label"
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content"
               android:text="Publisher:" />
          <TextView android:id="@+id/publisher"
               android:singleLine="true"
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content" />
          <TextView android:id="@+id/edition1_label"
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content"
               android:text="Edition:" />
          <TextView android:id="@+id/edition1" android:singleLine="true"
               android:layout_width="fill_parent" 			
               android:layout_height="wrap_content" />
          <TextView android:layout_width="fill_parent" 
               android:id="@+id/title1_label"
               android:layout_height="wrap_content" android:text="Title:" />
          <TextView android:id="@+id/title1" 			
               android:singleLine="true" android:layout_width="fill_parent"
               android:layout_height="wrap_content" />
          <TextView android:layout_width="fill_parent" 
               android:id="@+id/author1_label"
               android:layout_height="wrap_content" android:text="Author:" />

          <TextView android:id="@+id/author1" android:singleLine="true"
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content" />
          <TextView android:id="@+id/edition2_label"
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content"
               android:text="Edition:" />


          <TextView android:id="@+id/edition2" android:singleLine="true"
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content" />
          <TextView android:layout_width="fill_parent" 
               android:id="@+id/title2_label"
               android:layout_height="wrap_content" android:text="Title:" />
          <TextView android:id="@+id/title2" 			
               android:singleLine="true" android:layout_width="fill_parent"
               android:layout_height="wrap_content" />
          <TextView android:layout_width="fill_parent" 
               android:id="@+id/author2_label"
               android:layout_height="wrap_content" android:text="Author:" />
          <TextView android:id="@+id/author2" android:singleLine="true"
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content" />
</LinearLayout>

In the AndroidManifest.xml file, specify:

  • The activity to launch as ParsingXML
  • Minimum Android version 11 with the uses-sdk element
  • activity, intent-filter, and action with the activity element and subelements

Listing 15 shows the resulting AndroidManifest.xml file:

Listing 15. Configuration file, AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="android.xml"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="11" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ParsingXML"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

To parse the XML document resource, the example uses the android.content.res.XmlResourceParser, which extends the XmlPullParser interface. You need to create a directory in the res directory for the XML document.

  1. Create a directory called xml in the res directory, then copy the XML document catalog.xml to the res/xml directory.
  2. In the ParsingXML activity class, import the android.content.res.XmlResourceParser and org.xmlpull.v1.XmlPullParser interfaces.

    The onCreate(Bundle savedInstanceState) method is invoked when the activity is started.

  3. In the onCreate method, set the UI using the setContentView method and the layout resource, like so: setContentView(R.layout.main);
  4. Get the Android TextView widgets defined in the main.xml file using the findViewById method and the widget ids, as in Listing 16.
Listing 16. Get TextView widgets
TextView journal = (TextView) findViewById(R.id.journal);
TextView publisher = (TextView) findViewById(R.id.publisher);
TextView edition1 = (TextView) findViewById(R.id.edition1);
TextView title1 = (TextView) findViewById(R.id.title1);
TextView author1 = (TextView) findViewById(R.id.author1);
TextView edition2 = (TextView) findViewById(R.id.edition2);
TextView title2 = (TextView) findViewById(R.id.title2);
TextView author2 = (TextView) findViewById(R.id.author2);

Create an XmlResourceParser object from the catalog.xml document in the res/xml directory with the following code: XmlResourceParser xpp = getResources().getXml(R.xml.catalog);.

You will parse the XML document using the XmlResourceParser, which is also a pull parser (it extends the XmlPullParser interface). With the pull parser, an XML document is just a sequence of parsing events. Obtain the next parsing event using the next() method, as follows: xpp.next();.

Obtain the event type using the getEventType method int, which returns an int: eventType = xpp.getEventType();.

The returned int might have one of the values in Table 1.

Table 1. Event types int values
int ValueDescription
COMMENTAn XML comment
DOCDECLXML document type declaration
END_DOCUMENTDocument end
END_TAGEnd of an element tag
IGNORABLE_WHITESPACEIgnorable whitespace
PROCESSING_INSTRUCTIONProcessing instruction
START_DOCUMENTStart of a document
START_TAGStart of an element tag
TEXTCharacter data

The XML document has only elements and element text nodes to parse. Attributes do not generate an event, and you can retrieve them from an element. You'll find only the START_TAG and TEXT event types, which correspond with element start tags and element text nodes. First, determine the element tag and then get the text node value for the element tag. Use the int variable iter to indicate the different "article" elements in the XML document, and the String variable elemtext to specify the element tag name. To specify an int variable for an iterator and a String variable for element name, use the code in Listing 17.

Listing 17. Specify variables
int iter = 0;
String elemtext = null;

Before the end of the XML document is reached:

  • Determine the event types
  • Obtain the element tag names and element tag text values
  • Set the text node values on the corresponding TextView widgets

For example, get the element tag name as in Listing 18.

Listing 18. Get element names for start tags
while (eventType != XmlPullParser.END_DOCUMENT) {
              if (eventType == XmlPullParser.START_TAG) {
         String elemName = xpp.getName();
...
...
                                                         }
                                                 }

If the element tag name is "catalog", obtain the attribute values for "journal" and "publisher" and set the attribute values on the "journal" and "publisher" TextView widgets. Use the getAttributeValue() method of the XmlResourceParser to get the attribute values, as in Listing 19.

Listing 19. Get and set attribute values
if (elemName.equals("catalog")) {			
String journalAttr = xpp.getAttributeValue(null,"journal");
String publisherAttr = xpp.getAttributeValue(null,"publisher");
journal.setText(journalAttr);				
publisher.setText(publisherAttr);	
...
}

Increment the iterator variable iter for each "article" element, as in Listing 20.

Listing 20. Increment the variable
if (elemName.equals("article")) {
     iter = iter + 1;
                                 }

Obtain the text node values if the event type is TEXT and set the text node values on the corresponding TextView widgets. Use the elemtextString variable, which was set for event type START_TAG, to get the element tag name. Use the getText() method of the XmlResourceParser to get the text node value. Set the text node values on the TextView widgets using the setText method, as in Listing 21.

Listing 21. Get text node values
else if (eventType == XmlPullParser.TEXT) {
//Obtain the element name and element text node values and 
//set the text node values on the corresponding TextView 
//widgets
}

Listing 22 shows the Activity class ParsingXML.

Listing 22. Activity Class ParsingXML
package android.xml;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import android.content.res.XmlResourceParser;

public class ParsingXML extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         //setContentView(R.layout.main);
         setContentView(R.layout.relativelayout);
         TextView journal = (TextView) findViewById(R.id.journal);
         TextView publisher = (TextView) findViewById(R.id.publisher);
         TextView edition1 = (TextView) findViewById(R.id.edition1);
         TextView title1 = (TextView) findViewById(R.id.title1);
         TextView author1 = (TextView) findViewById(R.id.author1);

         TextView edition2 = (TextView) findViewById(R.id.edition2);
         TextView title2 = (TextView) findViewById(R.id.title2);
         TextView author2 = (TextView) findViewById(R.id.author2);
         try {
              XmlResourceParser xpp = getResources().getXml(R.xml.catalog);
			
              xpp.next();
              int eventType = xpp.getEventType();
              int iter = 0;
              String elemtext = null;

              while (eventType != XmlPullParser.END_DOCUMENT) {

                 if (eventType == XmlPullParser.START_TAG) {

                     String elemName = xpp.getName();
                     if (elemName.equals("catalog")) {
                 String journalAttr = xpp.getAttributeValue(null,
                                  "journal");
                 String publisherAttr = xpp.getAttributeValue(null,
                                  "publisher");
                        journal.setText(journalAttr);
                        publisher.setText(publisherAttr);
                     }
                     if (elemName.equals("article")) {
                        iter = iter + 1;
                     }
					
                     if (elemName.equals("edition")) {
                        elemtext = "edition";
                     }
                     if (elemName.equals("title")) {
                        elemtext = "title";
                     }
                     if (elemName.equals("author")) {
                        elemtext = "author";
                     }
                 }

                 else if (eventType == XmlPullParser.TEXT) {
                     if (iter == 1) {
                        if (elemtext.equals("edition")) {
                             edition1.setText(xpp.getText());
                        } else if (elemtext.equals("title")) {
                             title1.setText(xpp.getText());
                        } else if (elemtext.equals("author")) {
                             author1.setText(xpp.getText());
                        }
                     }

                     else if (iter == 2) {
                        if (elemtext.equals("edition")) {
                             edition2.setText(xpp.getText());
                        } else if (elemtext.equals("title")) {
                             title2.setText(xpp.getText());
                        } else if (elemtext.equals("author")) {
                             author2.setText(xpp.getText());
                        }

                     }
                 }
                 eventType = xpp.next();
              }

         } catch (XmlPullParserException e) {
         } catch (IOException e) {
         }

    }
}

To run the Android application, right-click on the ParsingXML application and select Run As > Android Application, as in Figure 7.

Figure 7. Run an Android application to parse an XML document
Screen capture of running the Android application to parse an XML document

The Android AVD starts, and the ParsingXML application installs on the Android device, as in Figure 8.

Figure 8. ParsingXML application installed on an Android device
Screen capture of the ParsingXML application installed on an Android device

Click on the ParsingXML application to start the application activity. The XML document catalog.xml is parsed and output to the Android device, as in Figure 9.

Figure 9. XML document node values obtained by parsing
Screen capture of XML Document node values obtained by parsing

The element labels and element text nodes are stacked vertically. A layout in which the text node values are to the right of the corresponding labels would be preferable. For a custom layout with the text node values to the right of the labels, use RelativeLayout instead of LinearLayout. Use the android:layout_marginLeft attribute of the TextView widget for the text node values to appear to the right of the labels. Use the android:layout_below attribute to make the text node values appear below the text node values in the preceding row.

RelativeLayout provides other attributes, such as android:layout_toRightOf, to output a widget to the right of another widget and android:layout_toLeftOf to output a component to the left of another component. Listing 23 shows the main.xml for a relative layout.

Listing 23. Relative layout
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:padding="5px">

          <TextView android:id="@+id/journal_label"
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content"
               android:text="Journal:" />

          <TextView android:id="@+id/journal"  
               android:layout_marginLeft="50px"
               android:layout_width="fill_parent"
               android:layout_height="wrap_content" />

          <TextView android:id="@+id/publisher_label" 
               android:layout_below="@id/journal_label"
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content"
               android:text="Publisher:" />

          <TextView android:id="@+id/publisher"
               android:layout_below="@id/journal"
               android:layout_marginLeft="70px"
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content" />

          <TextView android:id="@+id/edition1_label"  
               android:layout_below="@id/publisher_label"
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content"
               android:text="Edition:" />

          <TextView android:id="@+id/edition1" 
               android:layout_below="@id/publisher"
               android:layout_width="fill_parent" 
               android:layout_marginLeft="50px"
               android:layout_height="wrap_content" />

          <TextView android:layout_width="fill_parent" 
               android:id="@+id/title1_label" 
               android:layout_below="@id/edition1_label"
               android:layout_height="wrap_content" 
               android:text="Title:" />

          <TextView android:id="@+id/title1" 
               android:layout_marginLeft="40px" 
               android:layout_below="@id/edition1"
               android:layout_width="fill_parent"
               android:layout_height="wrap_content" />

          <TextView android:layout_width="fill_parent" 
               android:id="@+id/author1_label" 
               android:layout_below="@id/title1_label"
               android:layout_height="wrap_content" 
               android:text="Author:" />

          <TextView android:id="@+id/author1" 
               android:layout_below="@id/title1"
               android:layout_width="fill_parent" 
               android:layout_marginLeft="50px"
               android:layout_height="wrap_content" />

          <TextView android:id="@+id/edition2_label" 
               android:layout_below="@id/author1_label"
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content"
               android:text="Edition:" />

          <TextView android:id="@+id/edition2" 
               android:layout_below="@id/author1"
               android:layout_width="fill_parent" 
               android:layout_marginLeft="50px"
               android:layout_height="wrap_content" />

          <TextView android:layout_width="fill_parent" 
               android:id="@id/title2_label" 
               android:layout_below="@id/edition2_label"
               android:layout_height="wrap_content" 
               android:text="Title:" />

          <TextView android:id="@+id/title2" 
               android:layout_marginLeft="40px" 
               android:layout_below="@id/edition2"
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content" />

          <TextView android:layout_width="fill_parent" 
               android:id="@+id/author2_label" 
               android:layout_below="@id/title2_label"
               android:layout_height="wrap_content" 
               android:text="Author:" />

          <TextView android:id="@+id/author2" 
               android:layout_below="@id/title2"
               android:layout_width="fill_parent" 
               android:layout_marginLeft="50px"
               android:layout_height="wrap_content" />

</RelativeLayout>

Rerun the ParsingXML application after you modify the layout. The XML document parses and outputs node values in the specified layout, as in Figure 10.

Figure 10. Formatted XML document node values
Screen capture of the formatted XML Document node values

Summary

You can create and parse an XML document on the Android 3.0 platform, which is used for both smartphones and mobile tablets. In the examples in this article, you used the standard DocumentBuilder and Transformer APIs on Android to create an XML document. You learned to use XMLResourceParser, which extends the XmlPullParser, to parse an XML document.


Download

DescriptionNameSize
Android XML Eclipse applicationandroid-xml-sourcecode.zip149KB

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into XML on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML, Open source
ArticleID=765422
ArticleTitle=Create and parse XML on the Android 3.0 platform
publish-date=04102012