android-xml-parsing-dom-icoderslab

Android XML Parsing Using DOM.

Android XML parsing using DOM Tutorial

There are many ways to parse XML, the most popular and widely used is DOM (Document Object Model). In this tutorial we will learn about Android XML parsing using DOM.

What Is Document Object Model (DOM)?

The Document Object Model (DOM) is an application programming interface (API) for valid XML documents. It defines the structure of document and the way it is accessed. In the abbreviation DOM, the term “document” is used in the broad sense — increasingly,we use XML because it is easy to learn and much more clearer, and much of this would traditionally be seen as data rather as documents. Nevertheless, XML sees this data as a document and presents that to DOM.

With the Document Object Model, programmers can build documents, navigate their structure, and add, modify, or delete elements and content. Anything found in an XML document can be accessed, modified, removed, or added using the Document Object Model, with a few modifications, in particular, the DOM interfaces for the XML internal and external subsets have not yet been specified.

What Is XML?

XML is abbreviation of extensible markup language, it’s both human and machine readable. XML plays an important part in the IT industry. For this purpose, it is important for all software engineers to have a thorough understanding of XML.

The building block of an XML document is an element, defined by tags. An element has a beginning and an ending tag. All elements in an XML document are contained in an outermost element known as the parent element. XML can also support nesting of elements, or elements within elements (child elements). This ability allows XML to form a hierarchical pattern. Element names describe the content of the element, and the structure describes the relationship between the elements.

 

Necessary imports for the application

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

Start by creating a new project in Android Studio

1

After typing the name and package name for your project click next.

2

Select empty activity from the options and click next leave the other one as default and click finish.

Step#1

Create an assets directory in your main folder. Then create a file, name it whatever you like. In this case, I’m going to name it ‘file.xml.’ I’m expecting that you have some basic understanding of XML, so write some XML in the newly created file, like this.

<?xml version="1.0"?>
<records>
    <employee>
        <name>Monica Geller</name>
        <profession>Chef</profession>
    </employee>
    <employee>
        <name>Ross Geller</name>
        <profession>paleontologist</profession>
    </employee>
    <employee>
        <name>Rachel Green</name>
        <profession>Waitress</profession>
    </employee>
    <employee>
        <name>Chandler Bing</name>
        <profession>Data Analyst</profession>
    </employee>
    <employee>
        <name>Joey Tribianni</name>
        <profession>Actor</profession>
    </employee>
    <employee>
        <name>Phoebe Buffay</name>
        <profession>Masseuse</profession>
    </employee>
</records>

file

Step#2

Now, open up your activity_main.xml and make a simple text view.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_parser"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#b99a8e"
    tools:context="icoderslab.com.xmlparsing.parser">

    <TextView
        android:id="@+id/name"
        android:layout_marginTop="30dp"
        android:layout_marginStart="100dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp" />

</LinearLayout>

look my screenshot for help

xml

Step#3

Okay, now you need to write code to extract the data out of it. But first you need an inputreader to read your xml file.

InputStream is = getAssets().open(“file.xml”);  // the xml file to parse

Then.

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

Document doc = dBuilder.parse(is);

Element element=doc.getDocumentElement();

element.normalize();

As we have employee as our parent tag so we’ll search it by its name.

NodeList nList = doc.getElementsByTagName (“employee”);

The for loop will extract every data out of the XML.

code

Step#4

Write a method getValue() which we need to get the respective information of the same node.

getval

package icoderslab.com.xmlparsing;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class parser extends AppCompatActivity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parser);

        LinearLayout layout = (LinearLayout) findViewById(R.id.activity_parser);

        try {
            InputStream in = getAssets().open("file.xml");
            DocumentBuilderFactory docb = DocumentBuilderFactory.newInstance();
            DocumentBuilder doc = docb.newDocumentBuilder();
            Document d = doc.parse(in);
            Element element = d.getDocumentElement();
            element.normalize();

            NodeList nodeList = d.getElementsByTagName("employee");
            for (int i = 0; i < nodeList.getLength(); i++) {

                TextView text1 = new TextView(this);
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element2 = (Element) node;
                    text1.setTextSize(15);
                    text1.setTextColor(0xFFFF0000);
                    text1.setText(text1.getText()  + "Name: " +  getValue("name", element2) + "\n");
                    text1.setText(text1.getText()  + "Profession: " + getValue("profession", element2) + "\n");
                    layout.addView(text1);
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }


    }


    public static String getValue(String tag, Element e) {

        NodeList node = e.getElementsByTagName(tag).item(0).getChildNodes();
        Node nodes = node.item(0);
        return nodes.getNodeValue();

    }


}

Step#5

Now run your app and see how DOM extracts data and displays it on your screen. You are done with  Android XML parsing using DOM.

OUTPUT:

Android XML Parsing Using DOM output
Android XML Parsing Using DOM output

 

Download Code

By: Abeer Qamer

Leave a Reply

Your email address will not be published. Required fields are marked *