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.
To follow along with the examples in this article, install and configure the following software See Resources for links.
- Install the Eclipse IDE.
- Install the Android Development Tools (ADT) plug-in for Eclipse, which provides a set of extensions to develop Android applications in Eclipse.
- Download and install the Android SDK Platform, which provides tools for developing Android applications.
- Select Window > Android SDK, and AVD Manager, to launch the Android SDK and AVD Manager in Eclipse.
- 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.
In this section, you create an XML document on Android. The first step is to create an Android project.
- In the Eclipse IDE, select File > New. In the New dialog, select Android > Android Project. Click Next.
- 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 theActivityclass creates a window for a UI. - Minimum SDK Version: 11
- Application name:
Figure 1. Create an Android project for platform 3.0
- Project name:
- Click Next.
- 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.
- An activity class,
Figure 2 shows the directory structure of the Android project CreatingXML.
Figure 2. Android project to create 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.DocumentBuilderclass javax.xml.parsers.DocumentBuilderFactoryclass-
org.w3c.dompackage -
javax.xml.transform.TransformerFactoryclass -
javax.xml.transform.Transformerclass -
javax.xml.transform.dom.DOMSourceclass javax.xml.transform.stream.StreamResultclass
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
Documentobject to aByteArrayOutputStream - Obtain the XML document as a string from the
OutputStream - Set the string on the
TextViewwidget 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
The Android AVD starts and the Android application deploys on the AVD, as in Figure 4.
Figure 4. 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
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.
- In the Eclipse IDE, select File > New. In the New dialog, select Android > Android Project. Click Next.
- 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
- Application name:
Figure 6. Create an Android project for parsing an XML document
- Project name:
- Click Finish.
An Android project is created. It consists of:
- An
ActivityclassParsingXML - A res/layout/main.xml file for layout
- An AndroidManifest.xml file for application configuration
- An
Parse the XML document and use labels to output the element values.
The labels and element text node values are output to TextView widgets.
- In the main.xml file, add a
TextViewwidget for each label and element text node value. - Create a
LinearLayoutand setandroid:orientationto"vertical". - Add the
TextViewelements 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
activityto launch asParsingXML - Minimum Android version 11 with the
uses-sdkelement activity,intent-filter, andactionwith 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.
- Create a directory called xml in the res directory, then copy the XML document catalog.xml to the res/xml directory.
- In the
ParsingXMLactivity 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. - In the
onCreatemethod, set the UI using thesetContentViewmethod and the layout resource, like so:setContentView(R.layout.main); - Get the Android
TextViewwidgets defined in the main.xml file using thefindViewByIdmethod 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 Value | Description |
|---|---|
| COMMENT | An XML comment |
| DOCDECL | XML document type declaration |
| END_DOCUMENT | Document end |
| END_TAG | End of an element tag |
| IGNORABLE_WHITESPACE | Ignorable whitespace |
| PROCESSING_INSTRUCTION | Processing instruction |
| START_DOCUMENT | Start of a document |
| START_TAG | Start of an element tag |
| TEXT | Character 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
TextViewwidgets
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 elemtext String 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
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
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
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
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.
| Description | Name | Size | Download method |
|---|---|---|---|
| Android XML Eclipse application | android-xml-sourcecode.zip | 149KB | HTTP |
Information about download methods
Learn
- Android: Learn how to create Android applications.
- Working with XML on Android (Michael Galpin, developerWorks, June 2009): Explore different options for working with XML on Android as you build your own Android apps in this review of XML APIs for Android.
- Build dynamic user interfaces with Android and XML (Frank Ableson, developerWorks, September 2010): Learn about a simple architecture for designing similar applications for Android—dynamic user interfaces that allow non-programmers to collect data from mobile users.
- Using XML and JSON with Android, Part 1: Explore the benefits of JSON and XML in Android applications (Frank Ableson, developerWorks, August 2010): Get the basics of XML and JSON. Learn how to build an Android application that parses and displays a Twitter status-update feed provided in both formats.
- Using XML and JSON with Android, Part 2: Deliver hybrid Android applications with JSON (Frank Ableson, developerWorks, August 2010): Explore how to use a mix of JavaScript, JSON, callback functions, and Android-SDK Java code for flexible mobile apps.
- Android content on developerWorks: Explore articles, demos, and tutorials about Android.
- More articles by this author (Deepak Vohra, developerWorks, April 2005-current): Read articles about Android, Ajax, PHP, XML, web services, Ruby on Rails, EJB, and other technologies.
- New to XML? Get the resources you need to learn XML.
- XML area on developerWorks: Find the resources you need to advance your skills in the XML arena, including DTDs, schemas, and XSLT. See the XML technical library for a wide range of technical articles and tips, tutorials, standards, and IBM Redbooks.
- IBM XML certification: Find out how you can become an IBM-Certified Developer in XML and related technologies.
- developerWorks technical events and webcasts: Stay current with technology in these sessions.
- developerWorks on Twitter: Join today to follow developerWorks tweets.
- developerWorks podcasts: Listen to interesting interviews and discussions for software developers.
- developerWorks on-demand demos: Watch demos ranging from product installation and setup for beginners to advanced functionality for experienced developers.
Get products and technologies
- Android SDK: Get the latest tools or platform.
- Android Development Tools (ADT): Download this plug-in that gives you a powerful, integrated environment in which to build Android applications.
- JDK 6.0.: Get the latest Java™ releases, including performance improvements and bug fixes.
- Eclipse for Java EE.: Download the latest version.
- IBM product evaluation versions: Download or explore the online trials in the IBM SOA Sandbox and get your hands on application development tools and middleware products from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere®.
Discuss
- developerWorks profile: Create your profile today and set up a watchlist on the Blogger Data API.
- XML zone discussion forums: Participate in any of several XML-related discussions.
- The developerWorks community: Connect with other developerWorks users while exploring the developer-driven blogs, forums, groups, and wikis.



