Android XML Parsing Tutorial – Using DOMParser

Moving ahead from Android XML Parsing using SAXParser, here we are going to see about how to parse a XML using DOM Parser.
we are going to parse XML from net ( by passing URL ) not from local file or string.

The output looks similar to

example.xml ( )

[sourcecode language="xml"]
<website category="android"></website>
<website category="iPhone"></website>

This is main activity class. when App. starts this file will be called first.
This file contains how to use DOM Parser to handle XML tags.

[sourcecode language="java"]
package com.androidpeople.xml.parsing;


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.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class XMLParsingDOMExample extends Activity {

public void onCreate(Bundle savedInstanceState) {

/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);

/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView category[];

try {

URL url = new URL(
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));

NodeList nodeList = doc.getElementsByTagName("item");

/** Assign textview array lenght by arraylist size */
name = new TextView[nodeList.getLength()];
website = new TextView[nodeList.getLength()];
category = new TextView[nodeList.getLength()];

for (int i = 0; i < nodeList.getLength(); i++) {

Node node = nodeList.item(i);

name[i] = new TextView(this);
website[i] = new TextView(this);
category[i] = new TextView(this);

Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
name[i].setText("Name = "
+ ((Node) nameList.item(0)).getNodeValue());

NodeList websiteList = fstElmnt.getElementsByTagName("website");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
website[i].setText("Website = "
+ ((Node) websiteList.item(0)).getNodeValue());

category[i].setText("Website Category = "
+ websiteElement.getAttribute("category"));


} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);

/** Set the layout view to display */



You can download the full source code here

Android XML Parsing using SAXParser


Balakrishnan, It will work in

It will work in old version also.

Clark, wat error you are


wat error you are getting ?

Hi The xml is still

The xml is still alive.
Chk ur internet connection b4 starting the application.

@sathishbabu, Paste your


Paste your logcat error message