Android Simple XML Parsing Using DOM Tutorial

In this tutorial, you will learn how to parse an XML file into your Android application. In an XML document, an object represents the contents of the page and manipulates it using a DOM Parser. We will create an AsyncTask to download an XML file from our server and use a DOM Parser to manipulate the results into a TextView. So lets begin…

Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project XMLParseTutorial.

Application Name : XMLParseTutorial

Project Name : XMLParseTutorial

Package Name : com.androidbegin.xmlparsetutorial

Open your MainActivity.java and paste the following code.

MainActivity.java

package com.androidbegin.xmlparsetutorial;

import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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 android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {
	// Declare variables
	TextView textview;
	NodeList nodelist;
	ProgressDialog pDialog;
	// Insert image URL
	String URL = "https://www.androidbegin.com/tutorial/XMLParseTutorial.xml";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from activity_main.xml
		setContentView(R.layout.activity_main);
		// Locate a TextView in your activity_main.xml layout
		textview = (TextView) findViewById(R.id.text);
		// Execute DownloadXML AsyncTask
		new DownloadXML().execute(URL);
	}

	// DownloadXML AsyncTask
	private class DownloadXML extends AsyncTask<String, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressbar
			pDialog = new ProgressDialog(MainActivity.this);
			// Set progressbar title
			pDialog.setTitle("Android Simple XML Parsing using DOM Tutorial");
			// Set progressbar message
			pDialog.setMessage("Loading...");
			pDialog.setIndeterminate(false);
			// Show progressbar
			pDialog.show();
		}

		@Override
		protected Void doInBackground(String... Url) {
			try {
				URL url = new URL(Url[0]);
				DocumentBuilderFactory dbf = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				// Download the XML file
				Document doc = db.parse(new InputSource(url.openStream()));
				doc.getDocumentElement().normalize();
				// Locate the Tag Name
				nodelist = doc.getElementsByTagName("item");

			} catch (Exception e) {
				Log.e("Error", e.getMessage());
				e.printStackTrace();
			}
			return null;

		}

		@Override
		protected void onPostExecute(Void args) {

			for (int temp = 0; temp < nodelist.getLength(); temp++) {
				Node nNode = nodelist.item(temp);
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {
					Element eElement = (Element) nNode;
					// Set the texts into TextViews from item nodes
					// Get the title
					textview.setText(textview.getText() + "Title : "
							+ getNode("title", eElement) + "\n" + "\n");
					// Get the description
					textview.setText(textview.getText() + "Description : "
							+ getNode("description", eElement) + "\n" + "\n");
					// Get the link
					textview.setText(textview.getText() + "Link : "
							+ getNode("link", eElement) + "\n" + "\n");
					// Get the date
					textview.setText(textview.getText() + "Date : "
							+ getNode("date", eElement) + "\n" + "\n" + "\n"
							+ "\n");
				}
			}
			// Close progressbar
			pDialog.dismiss();
		}
	}

	// getNode function
	private static String getNode(String sTag, Element eElement) {
		NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
				.getChildNodes();
		Node nValue = (Node) nlList.item(0);
		return nValue.getNodeValue();
	}
}

When the application launches this activity will start to download an XML object from the URL address. The downloaded XML objects are manipulated by using a DOM Parser and then use the getNode function to get the elements. Then populate the TextViews with the appropriate nodes and elements.

In this tutorial, we’ve hosted an XML file in our server. https://www.androidbegin.com/tutorial/XMLParseTutorial.xml

Next, create an XML file for your MainActivity graphical layout. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file activity_main.xml and paste the following code.

activity_main.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true" />
    </RelativeLayout>

</ScrollView>

Next, change the application name. Open your strings.xml in your res > values folder and paste the following code.
strings.xml

<resources>

    <string name="app_name">XMLParse Tutorial</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>

</resources>

In your AndroidManifest.xml, we need to declare a permission to allow the application to connect to the Internet. Open your AndroidManifest.xml and paste the following code.

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbegin.xmlparsetutorial"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Output:

XMLParse Tutorial ScreenShots

Source Code 

[purchase_link id=”7886″ text=”Purchase to Download Source Code” style=”button” color=”green”]

Latest comments

https://uploads.disquscdn.com/images/87491e676e415aed0684b0134a9d7e5c88e0c69678964c61249ae369e6eec9de.png

Dhawal Mathur

Android Simple XML Parsing Using DOM Tutorial

If i need to select another tag from xml in onPostExecute mathod, what should i do, here?

Nahid

Android Simple XML Parsing Using DOM Tutorial

hey ... I am not understand XML Parsing .... can you help me ... ??

Rana Saqib Manjj

Android Simple XML Parsing Using DOM Tutorial

thanks for awesome tutorial

garenyondem

Android Simple XML Parsing Using DOM Tutorial