articles

Home / DeveloperSection / Articles / Android XML Processing with the DOM Parser

Android XML Processing with the DOM Parser

Manoj Pandey4230 18-Feb-2015

In my last article, we learn about Multi-pane development in Android with Fragments(Multi-pane development in Android with Fragments).  Now we see how use Android XML Processing with the DOM Parser

There are three types of Android XML parsers – DOM, SAX and XmlPullParser.

Here is example of DOM. Document Object Modelis an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.

Here is an example XML file, and a DOM tree that illustrates the principle of turning XML into DOM:

<student>
    <id>101</id>
    <name>Zack</name>
    <age>25</age>
</student>

Android XML Processing with the DOM Parser

1.       Create your android project

2.      Add xml file in assets folder name should be student.xml and add following code 

student.xml contain records of student

<?xml version="1.0" encoding="UTF-8"?>

<data>

<student>

<id>101</id>

<name>Michel Belly </name>

<age>21</age>

</student>

 

<student>

<id>102</id>

<name>Adney</name>

<age>27</age>

</student>

<student>

<id>103</id>

<name>Aiken Starch</name>

<age>27</age>

</student>

 

<student>

<name>Abbott</name>

<age>26</age>

</student>

 

<student>

<id>104</id>

<name>Alif</name>

<age>19</age>

</student>

 

<student>

<id>105</id>

<name>Kaarle</name>

<age>23</age>

</student>

 

<student>

<id>106</id>

<name>Maarku</name>

<age>22</age>

</student>

 

<student>

<id>107</id>

<name>Rahul</name>

<age>20</age>

</student>

 

<student>

<id>108</id>

<name>Salomao</name>

<age>25</age>

</student>

 

<student>

<id>109</id>

<name>David Warner</name>

<age>21</age>

</student>

<student>

<id>10</id>

<name>Zack</name>

<age>18</age>

</student>

</data>



3.   Add listview in activity_main 

<?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">

     <!-- Main ListView

            Always give id value as list(@android:id/list)

     -->

    <ListView

        android:id="@android:id/list"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"/>

 

</LinearLayout>

 

4.  Create layout xml file for show custom listview item name should be list_item.xml

<?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="wrap_content"

    android:background="#ffffff"

    android:orientation="vertical" >

 

    <!-- Name Label -->

 

    <TextView

        android:id="@+id/name"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:paddingBottom="2dip"

        android:paddingTop="6dip"

        android:text="Name"

        android:textColor="#282828"

        android:textSize="16sp"

        android:textStyle="bold" />

    <!-- Description label -->

 

    <TextView

        android:id="@+id/age"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:paddingBottom="2dip"

        android:text="Age"

        android:textColor="#282828" >

    </TextView>

 

</LinearLayout>

 

5.  Add another layout xml file name should be select_item  and paste following code 

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical" >

 

    <!-- Name Label -->

 

    <TextView

        android:id="@+id/name_label"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:paddingBottom="10dip"

        android:paddingTop="10dip"

        android:textColor="#dc6800"

        android:textSize="25dip"

        android:textStyle="bold" />

    <!-- Age Label -->

 

    <TextView

        android:id="@+id/description_label"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:textColor="#acacac" /> 

 

</LinearLayout>

 

6.  Create an XMLParser class and paste following code 

package com.androidhive.xmlparsing; 

import org.w3c.dom.Element;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

 

public class XMLParser {

 

     // constructor

    

 

 

     /**

      * Getting node value

      *

      * @param elem

      *            element

      */

     public final String getElementValue(Node elem) {

           Node child;

           if (elem != null) { 

                if (elem.hasChildNodes()) {

                     for (child = elem.getFirstChild(); child != null; child = child

                                .getNextSibling()) {

                           if (child.getNodeType() == Node.TEXT_NODE) {

                                return child.getNodeValue();

                           }

                      }

                }

           }

           return "";

     }

 

     /**

      * Getting node value

      *

      * @param Element

      *            node

      * @param key

      *            string

      * */

     public String getValue(Element item, String str) {

           NodeList n = item.getElementsByTagName(str);

           return this.getElementValue(n.item(0));

     }

}

 

Add following code in MainActivity.class

package com.androidhive.xmlparsing;

 

import java.io.InputStream;

import java.util.ArrayList;

import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

 

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

 

import android.app.ListActivity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.AdapterView;

import android.widget.AdapterView.OnItemClickListener;

import android.widget.ListAdapter;

import android.widget.ListView;

import android.widget.SimpleAdapter;

import android.widget.TextView;

 

public class MainActivity extends ListActivity {

 

     // All static variables

     // static final String URL =

 

     static final String KEY_ITEM = "student"; // parent node

     static final String KEY_ID = "id";

     static final String KEY_NAME = "name";

     static final String KEY_AGE = "age";

 

     @Override

     public void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);

           setContentView(R.layout.main);

           try {

 

                ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

 

                XMLParser parser = new XMLParser();

                // InputStream is a readable source of bytes.

                InputStream isStream = getAssets().open("student.xml");

        // DocumentBuilderFactory defines a factory API that enables

        // applications to obtain a

        // parser that produces DOM object trees from XML documents.

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory

                           .newInstance();

            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

                Document doc = dBuilder.parse(isStream);

        // NodeList objects in the DOM are live.

     // The items in the NodeList are accessible via an integral index,

        // starting from 0.

                NodeList nl = doc.getElementsByTagName(KEY_ITEM);

 

                // looping through all item nodes <item>

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

                     // creating new HashMap

           HashMap<String, String> map = new HashMap<String, String>();

                     Element e = (Element) nl.item(i);

                     // adding each child node to HashMap key => value

                     map.put(KEY_ID, parser.getValue(e, KEY_ID));

          map.put(KEY_NAME, "Name -: " + parser.getValue(e, KEY_NAME));

          map.put(KEY_AGE, "Age -: " + parser.getValue(e, KEY_AGE));

                   // map.put(KEY_DESC, parser.getValue(e, KEY_DESC));

 

                     // adding HashList to ArrayList

                     menuItems.add(map);

                }

 

                // Adding menuItems to ListView

             ListAdapter adapter = new SimpleAdapter(this, menuItems,

                  R.layout.list_item, new String[] { KEY_NAME, KEY_AGE,

                         KEY_AGE }, new int[] { R.id.name, R.id.age });

 

                setListAdapter(adapter);

 

                // selecting single ListView item

                ListView lv = getListView();

 

               lv.setOnItemClickListener(new OnItemClickListener() {

 

                     @Override

              public void onItemClick(AdapterView<?> parent, View view,

                                int position, long id) {

                           // getting values from selected ListItem

              String name = ((TextView) view.findViewById(R.id.name))

                                     .getText().toString();

 

                           String description = ((TextView) view

                         .findViewById(R.id.age)).getText().toString();

 

                           // Starting new intent

                     Intent in = new Intent(getApplicationContext(),

                                     SingleMenuItemActivity.class);

                           // Pass value of selected item with intent

                           in.putExtra(KEY_NAME, name);

                           in.putExtra(KEY_AGE, description);

 

                           startActivity(in);

 

                     }

                });

           } catch (Exception ex) {

 

           }

     }

}

 

7.  Add another activity class name as SingleMenuItemActivity and add following code 

package com.androidhive.xmlparsing;

 

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.widget.TextView;

 

public class SingleMenuItemActivity extends Activity {

 

     // XML node keys

     static final String KEY_NAME = "name";

 

     static final String KEY_AGE = "age";

 

     @Override

     public void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);

           setContentView(R.layout.select_item);

 

           // getting intent data

           Intent in = getIntent();

 

           // Get XML values from previous intent

           String name = in.getStringExtra(KEY_NAME);

 

           String description = in.getStringExtra(KEY_AGE);

 

          // Displaying all values on the screen

           TextView lblName = (TextView) findViewById(R.id.name_label);

           TextView lblDesc = (TextView) findViewById(R.id.description_label);

           lblName.setText(name);

 

           lblDesc.setText(description);

     }

}

 

And now run your application

  Android XML Processing with the DOM Parser   Android XML Processing with the DOM Parser


Updated 07-Sep-2019

Leave Comment

Comments

Liked By