Android: Simple XML DOM parser

22 November 2012 By Nithya Vasudevan 27,578 views 5 Comments
7 Flares Twitter 0 Facebook 0 Google+ 7 7 Flares ×

Project Description

This Android code example shows how to parse a simple XML using DOM parser and display it in TextView.

Usually, we display the XML result in ListView or Spinner which is explained in tutorials Android: Parsing XML with children and attributes using DOM and Android XML DOM parser with AsyncTask.

  • In this example, we are going to store the XML file in project’s assets folder and open the file as InputStream using AssetManager.
  • On button click event, we parse the XML and display the result in TextView.

To parse an XML in Android, you can use DOM and SAX parser API provided by Java platform. In addition to these two parsers, Android provides XmlPullParser which is similar to StAX parser and also the recommended parser to be used in Android.

Environment Used

  • JDK 6 (Java SE 6)
  • Eclipse Indigo IDE for Java EE Developers (3.7.1)
  • Android SDK 4.0.3 / 4.1 Jelly Bean
  • Android Development Tools (ADT) Plugin for Eclipse (ADT version 20.0.0)
  • Refer this link to setup the Android development environment

Prerequisites

  • HelloWorld Example

Create Android Project

  • Create a new Android Project and name it as “SimpleDOMParser“.
  • Enter the package name as “com.theopentutorials.android.xml“.
  • Enter the Activity name as “DOMXMLParsingActivity“.
  • Click Finish.

Create XML file

In the project’s assets folder, create a new XML file and name it as “employee.xml” and copy the following.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
    <name>Kumar</name>
    <salary>30000.0</salary>
    <designation>Junior Developer</designation>
</employee>

strings.xml

Open res/values/string.xml and replace it with following content.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, DOMXMLParsingActivity!</string>
    <string name="app_name">SimpleDOMParser</string>
    <string name="button">Parse XML using DOM</string>
    <string name="nameLabel">Name</string>
    <string name="salaryLabel">Salary</string>
    <string name="designationLabel">Designation</string>
</resources>

XML layout file

This file defines a layout for displaying the result of DOM parsing in TextView.
Open main.xml file in res/layout and copy the following content.

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:columnCount="5" >

    <Button
        android:id="@+id/button"
        android:layout_column="0"
        android:layout_columnSpan="3"
        android:layout_gravity="center_horizontal"
        android:layout_row="0"
        android:text="@string/button" />

    <TextView
        android:id="@+id/nameLabel"
        android:layout_column="1"
        android:layout_gravity="left"
        android:layout_row="1"
        android:text="@string/nameLabel"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/nameText"
        android:layout_width="149dp"
        android:layout_column="2"
        android:layout_columnSpan="3"
        android:layout_row="1"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/salaryLabel"
        android:layout_column="1"
        android:layout_row="2"
        android:text="@string/salaryLabel"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/salaryText"
        android:layout_column="2"
        android:layout_row="2"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/designationLabel"
        android:layout_column="1"
        android:layout_row="3"
        android:text="@string/designationLabel"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/designationText"
        android:layout_column="2"
        android:layout_gravity="left"
        android:layout_row="3"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Space
        android:layout_width="21dp"
        android:layout_height="1dp"
        android:layout_column="0"
        android:layout_gravity="fill_horizontal"
        android:layout_row="0" />

    <Space
        android:layout_width="1dp"
        android:layout_height="81dp"
        android:layout_column="0"
        android:layout_gravity="fill_horizontal"
        android:layout_row="0" />

    <Space
        android:layout_width="134dp"
        android:layout_height="1dp"
        android:layout_column="1"
        android:layout_gravity="fill_horizontal"
        android:layout_row="0" />

    <Space
        android:layout_width="1dp"
        android:layout_height="53dp"
        android:layout_column="0"
        android:layout_gravity="fill_horizontal"
        android:layout_row="1" />

    <Space
        android:layout_width="1dp"
        android:layout_height="58dp"
        android:layout_column="0"
        android:layout_gravity="fill_horizontal"
        android:layout_row="2" />

</GridLayout>

Create XMLDOMParser class

package com.theopentutorials.android.xml;

import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;

public class XMLDOMParser {
	//Returns the entire XML document 
	public Document getDocument(InputStream inputStream) {
		Document document = null;
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder db = factory.newDocumentBuilder();
			InputSource inputSource = new InputSource(inputStream);
			document = db.parse(inputSource);
		} catch (ParserConfigurationException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (SAXException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		}
		return document;
	}

	/*
	 * I take a XML element and the tag name, look for the tag and get
	 * the text content i.e for <employee><name>Kumar</name></employee>
	 * XML snippet if the Element points to employee node and tagName 
	 * is name I will return Kumar. Calls the private method 
	 * getTextNodeValue(node) which returns the text value, say in our 
	 * example Kumar. */
	public String getValue(Element item, String name) {
		NodeList nodes = item.getElementsByTagName(name);
		return this.getTextNodeValue(nodes.item(0));
	}

	private final String getTextNodeValue(Node node) {
		Node child;
		if (node != null) {
			if (node.hasChildNodes()) {
				child = node.getFirstChild();
				while(child != null) {
					if (child.getNodeType() == Node.TEXT_NODE) {
						return child.getNodeValue();
					}
					child = child.getNextSibling();
				}
			}
		}
		return "";
	}
}

Create DOMXMLParsingActivity class

package com.theopentutorials.android.xml;

import java.io.IOException;
import java.io.InputStream;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class DOMXMLParsingActivity extends Activity implements OnClickListener {
	TextView nameText;
	TextView salaryText;
	TextView designationText;
	Button button;

	// XML node names
	static final String NODE_EMP = "employee";
	static final String NODE_NAME = "name";
	static final String NODE_SALARY = "salary";
	static final String NODE_DESIGNATION = "designation";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		findViewsById();

		button.setOnClickListener(this);
	}

	private void findViewsById() {
		nameText = (TextView) findViewById(R.id.nameText);
		salaryText = (TextView) findViewById(R.id.salaryText);
		designationText = (TextView) findViewById(R.id.designationText);
		button = (Button) findViewById(R.id.button);
	}

	public void onClick(View v) {
		XMLDOMParser parser = new XMLDOMParser();
		AssetManager manager = getAssets();
		InputStream stream;
		try {
			stream = manager.open("employee.xml");
			Document doc = parser.getDocument(stream);

			// Get elements by name employee
			NodeList nodeList = doc.getElementsByTagName(NODE_EMP);

			/*
			 * for each <employee> element get text of name, salary and
			 * designation
			 */
			// Here, we have only one <employee> element
			for (int i = 0; i < nodeList.getLength(); i++) {
				Element e = (Element) nodeList.item(i);
				nameText.setText(parser.getValue(e, NODE_NAME));
				salaryText.setText(parser.getValue(e, NODE_SALARY));
				designationText.setText(parser.getValue(e, NODE_DESIGNATION));
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.theopentutorials.android.xml"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.theopentutorials.android.xml.DOMXMLParsingActivity"
            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>

Output

Run your application

Project Folder Structure

The complete folder structure of this example is shown below.

Tags: , , , , , , , , , , , ,

  • JOE

    bonsoir! le tuto m’a été d’une grande utilité mais j’aimerai aussi savoir comment récupérer des données tapés sur un Editext et les insérées dans ce fichier xml? j’ai deja ce fichier et j’aimerai inserer d’autre chose. Merçi!

  • Pranav

    setContentView (R.Layout.main) cannot be resolved

  • Pranav

    this really worked thank you so much

  • Carlos Daniel

    Very usefull sample, thanks for share.

  • Mohammed Ahmad Osama

    I have multiple employees; what should i do???