XML Parsing Using DOM Parser in Android Studio

Introduction

In this article you will learn about XML Parsing using the DOM parser.

SDomParser

The DOM Parser is used to convert data from a server into a machine readable format.

Step 1


Create an XML File and write this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
   
android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

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

            android:layout_height="match_parent"

             android:layout_width="match_parent"

              />

 

</RelativeLayout>

Step 2

Create a Java File and write the following.

 

In this first we the string to the HTTP Client to get the stream from the server. And by using this Stream you will get the DOM element. Now you will apply parsing. 

package com.xmlparsingdomparser;

import android.app.ListActivity;

import android.app.ProgressDialog;

import android.content.Context;

import android.os.AsyncTask;

import android.os.Bundle;

import android.util.Log;

import android.view.Menu;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.util.EntityUtils;

import org.w3c.dom.Document;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

import org.xml.sax.SAXParseException;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

 

public class MainActivity extends ListActivity {

    private static String BASE_URL = "http://maps.googleapis.com/maps/api/geocode/xml?address=NewDelhi&sensor=false";

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        (new ProgressTask(MainActivity.this)).execute();

    }

  

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

       getMenuInflater().inflate(R.menu.main, menu);

        return true;

    } 

    public class ProgressTask extends AsyncTask<String, Void, Boolean> {

        private ProgressDialog dialog;

        private Context context;

        public ProgressTask(ListActivity activity) {

            Log.i("1", "Called");

            context = activity;

            dialog = new ProgressDialog(context);

        }

        protected void onPreExecute() {

            this.dialog.setMessage("Progress start");

            this.dialog.show();

        }

        @Override

        protected void onPostExecute(final Boolean success) {

            if (dialog.isShowing()) {

                dialog.dismiss();

            }

        }

        protected Boolean doInBackground(final String... args) {

           String xml = getXmlFromUrl(BASE_URL);

              userParserType2(xml);

            return null;

        }

        public void userParserType2 (String xml){

            try {

                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();

                DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

                Document doc = docBuilder.parse (xml);

                // normalize text representation

                System.out.println("firt:-"+doc.getDocumentElement ().getNodeName());

                NodeList listOfObject = doc.getDocumentElement().getChildNodes();

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

                {

                    if(listOfObject.item(i).getFirstChild()!=null&&listOfObject.item(i).getNodeName().equals("result"))

                    {

                      NodeList listOfResultChild=listOfObject.item(i).getChildNodes();

                        for(int j=0;j<listOfResultChild.getLength();j++)

                        {

                            if(listOfResultChild.item(j).getFirstChild()!=null&&listOfResultChild.item(j).getNodeName().equals("geometry"))

                            {

                                Node geometry=listOfResultChild.item(j);

                                NodeList geometryList=geometry.getChildNodes();

                                for(int k=0;k<geometryList.getLength();k++)

                                {

                                    if(geometryList.item(k).getFirstChild()!=null&&geometryList.item(k).getNodeName().equals("location"))

                                    {

                                        NodeList locationList=geometryList.item(k).getChildNodes();

                                        for(int l=0;l<locationList.getLength();l++)

                                        {

                                         if(locationList.item(l).getFirstChild()!=null)

                                            {

                                                System.out.println(locationList.item(l).getNodeName());

                                                System.out.println(locationList.item(l).getTextContent());

                                            }

                                        }

                                    }

                                }

 

 

                            }

                        }

 

                    }

                }

 

            }catch (SAXParseException err) {

                System.out.println ("** Parsing error" + ", line "

                        + err.getLineNumber () + ", uri " + err.getSystemId ());

                System.out.println(" " + err.getMessage ());

 

            }catch (SAXException e) {

                Exception x = e.getException ();

                ((x == null) ? e : x).printStackTrace ();

 

            }catch (Throwable t) {

                t.printStackTrace ();

            }

            //System.exit (0);

 

        }//end of main

 

 

    }

 

    public String getXmlFromUrl(String url) {

        String xml = null;

 

        try {

            // defaultHttpClient

            DefaultHttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url);

 

            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity httpEntity = httpResponse.getEntity();

            xml = EntityUtils.toString(httpEntity);

 

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        } catch (ClientProtocolException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

        // return XML

        return xml;

    }

 

}

 

Step 3

Android Manifest.Xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xmlparsingdomparser"
    android:versionCode="1"
    android:versionName="1.0" >
  <uses-sdk
      android:minSdkVersion="7"
      android:targetSdkVersion="16" />
  <uses-permission android:name="android.permission.INTERNET"/>
  <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
    <activity
        android:name="com.xmlparsingdomparser.MainActivity
  android:label="@string/app_name" >
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
 <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application> 
</manifest>

Step 4

Output

Progress.jpg

See the values in logcat:

LOGCAT.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all