Android XML Parsing using DOM Parser

The DOM parser can also be used to create and parse the XML file, just like the SAX parser.

Advantage of DOM Parser over SAX:

To parse the XML file, the SAX parser can be used, but cannot be used to create the XML file. The DOM parser can be used to do both.

Disadvantage of DOM Parser over SAX:

As compared to SAX, more memory is consumed by the DOM parser.

Example:

activity_main.xml

In the activity_main.xml file, we will drag a Textview from the palette.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/user_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:dividerHeight="1dp" />
</LinearLayout>

List_row.xml:

 <?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:orientation="horizontal"
    android:padding="5dip" >
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="17dp" />
    <TextView
        android:id="@+id/designation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_marginTop="7dp"
        android:textColor="#343434"
        android:textSize="14dp" />
    <TextView
        android:id="@+id/location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/designation"
        android:layout_alignBottom="@+id/designation"
        android:layout_alignParentRight="true"
        android:textColor="#343434"
        android:textSize="14dp" />
</RelativeLayout>

XML document:(File: userdetails.xml)

Inside the assets directory of the project, an XML file will be created.

<?xml version="1.0" encoding="utf-8"?>
 
<users>
 
    <user>
 
        <name>A</name>
 
        <designation>Leader</designation>
 
        <loation>City1</loation>
 
    </user>
 
    <user>
 
        <name>B</name>
 
        <designation>Secretary</designation>
 
        <loation>City2</loation>
 
    </user>
 
    <user>
 
        <name>C</name>
 
        <designation>Accountant</designation>
 
        <loation>City3</loation>
 
    </user>
 
    <user>
 
        <name>D</name>
 
        <designation>Officer 1</designation>
 
        <loation>City4</loation>
 
    </user>
 
    <user>
 
        <name>E</name>
 
        <designation>Officer 2</designation>
 
        <loation>City5</loation>
 
    </user>
 
</users>

Activity class(File: MainActivity.java)

In the MainActivity.java file, we will write the code to parse the XML using the DOM parser.

package com.example.radioapp;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try{
            ArrayList<HashMap<String, String>> userList = new ArrayList<>();
            ListView lv = (ListView) findViewById(R.id.user_list);
            InputStream istream = getAssets().open("userdetails.xml");
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(istream);
            NodeList nList = doc.getElementsByTagName("user");
            for(int i =0;i<nList.getLength();i++){
                if(nList.item(0).getNodeType() == Node.ELEMENT_NODE){
                    HashMap<String,String> user = new HashMap<>();
                    Element elm = (Element)nList.item(i);
                    user.put("name", getNodeValue("name",elm));
                    user.put("designation", getNodeValue("designation",elm));
                    user.put("location", getNodeValue("location",elm));
                    userList.add(user);
                }
            }
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, userList, R.layout.list_row,new String[]{"name","designation","location"}, new int[]{R.id.name, R.id.designation, R.id.location});
            lv.setAdapter(adapter);
        }
        catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }
    protected String getNodeValue(String tag, Element element) {
        NodeList nodeList = element.getElementsByTagName(tag);
        Node node = nodeList.item(0);
        if(node!=null){
            if(node.hasChildNodes()){
                Node child = node.getFirstChild();
                while (child!=null){
                    if(child.getNodeType() == Node.TEXT_NODE){
                        return  child.getNodeValue();
                    }
                }
            }
        }
        return "";
    }
}

Output: