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
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  6.     android:paddingRight="@dimen/activity_horizontal_margin"  
  7.     android:paddingTop="@dimen/activity_vertical_margin"  
  8.     android:paddingBottom="@dimen/activity_vertical_margin"  
  9.     tools:context=".MainActivity">  
  10.   <ListView android:id="@android:id/list"  
  11.             android:layout_height="match_parent"  
  12.              android:layout_width="match_parent"  
  13.               />  
  14.    
  15. </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. 
  1. package com.xmlparsingdomparser;  
  2. import android.app.ListActivity;  
  3. import android.app.ProgressDialog;  
  4. import android.content.Context;  
  5. import android.os.AsyncTask;  
  6. import android.os.Bundle;  
  7. import android.util.Log;  
  8. import android.view.Menu;  
  9. import org.apache.http.HttpEntity;  
  10. import org.apache.http.HttpResponse;  
  11. import org.apache.http.client.ClientProtocolException;  
  12. import org.apache.http.client.methods.HttpPost;  
  13. import org.apache.http.impl.client.DefaultHttpClient;  
  14. import org.apache.http.util.EntityUtils;  
  15. import org.w3c.dom.Document;  
  16. import org.w3c.dom.Node;  
  17. import org.w3c.dom.NodeList;  
  18. import org.xml.sax.SAXException;  
  19. import org.xml.sax.SAXParseException;  
  20. import javax.xml.parsers.DocumentBuilder;  
  21. import javax.xml.parsers.DocumentBuilderFactory;  
  22. import java.io.IOException;  
  23. import java.io.UnsupportedEncodingException;  
  24.    
  25. public class MainActivity extends ListActivity {  
  26.     private static String BASE_URL = "http://maps.googleapis.com/maps/api/geocode/xml?address=NewDelhi&sensor=false";  
  27.     @Override  
  28.     protected void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.         setContentView(R.layout.activity_main);  
  31.         (new ProgressTask(MainActivity.this)).execute();  
  32.     }  
  33.     
  34.     @Override  
  35.     public boolean onCreateOptionsMenu(Menu menu) {  
  36.        getMenuInflater().inflate(R.menu.main, menu);  
  37.         return true;  
  38.     }   
  39.     public class ProgressTask extends AsyncTask<String, Void, Boolean> {  
  40.         private ProgressDialog dialog;  
  41.         private Context context;  
  42.         public ProgressTask(ListActivity activity) {  
  43.             Log.i("1""Called");  
  44.             context = activity;  
  45.             dialog = new ProgressDialog(context);  
  46.         }  
  47.         protected void onPreExecute() {  
  48.             this.dialog.setMessage("Progress start");  
  49.             this.dialog.show();  
  50.         }  
  51.         @Override  
  52.         protected void onPostExecute(final Boolean success) {  
  53.             if (dialog.isShowing()) {  
  54.                 dialog.dismiss();  
  55.             }  
  56.         }  
  57.         protected Boolean doInBackground(final String... args) {  
  58.            String xml = getXmlFromUrl(BASE_URL);  
  59.               userParserType2(xml);  
  60.             return null;  
  61.         }  
  62.         public void userParserType2 (String xml){  
  63.             try {  
  64.                 DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();  
  65.                 DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();  
  66.                 Document doc = docBuilder.parse (xml);  
  67.                 // normalize text representation  
  68.                 System.out.println("firt:-"+doc.getDocumentElement ().getNodeName());  
  69.                 NodeList listOfObject = doc.getDocumentElement().getChildNodes();  
  70.                 for(int i=0;i<listOfObject.getLength();i++)  
  71.                 {  
  72.                     if(listOfObject.item(i).getFirstChild()!=null&&listOfObject.item(i).getNodeName().equals("result"))  
  73.                     {  
  74.                       NodeList listOfResultChild=listOfObject.item(i).getChildNodes();  
  75.                         for(int j=0;j<listOfResultChild.getLength();j++)  
  76.                         {  
  77.                             if(listOfResultChild.item(j).getFirstChild()!=null&&listOfResultChild.item(j).getNodeName().equals("geometry"))  
  78.                             {  
  79.                                 Node geometry=listOfResultChild.item(j);  
  80.                                 NodeList geometryList=geometry.getChildNodes();  
  81.                                 for(int k=0;k<geometryList.getLength();k++)  
  82.                                 {  
  83.                                     if(geometryList.item(k).getFirstChild()!=null&&geometryList.item(k).getNodeName().equals("location"))  
  84.                                     {  
  85.                                         NodeList locationList=geometryList.item(k).getChildNodes();  
  86.                                         for(int l=0;l<locationList.getLength();l++)  
  87.                                         {  
  88.                                          if(locationList.item(l).getFirstChild()!=null)  
  89.                                             {  
  90.                                                 System.out.println(locationList.item(l).getNodeName());  
  91.                                                 System.out.println(locationList.item(l).getTextContent());  
  92.                                             }  
  93.                                         }  
  94.                                     }  
  95.                                 }  
  96.    
  97.    
  98.                             }  
  99.                         }  
  100.    
  101.                     }  
  102.                 }  
  103.    
  104.             }catch (SAXParseException err) {  
  105.                 System.out.println ("** Parsing error" + ", line "  
  106.                         + err.getLineNumber () + ", uri " + err.getSystemId ());  
  107.                 System.out.println(" " + err.getMessage ());  
  108.    
  109.             }catch (SAXException e) {  
  110.                 Exception x = e.getException ();  
  111.                 ((x == null) ? e : x).printStackTrace ();  
  112.    
  113.             }catch (Throwable t) {  
  114.                 t.printStackTrace ();  
  115.             }  
  116.             //System.exit (0);  
  117.    
  118.         }//end of main  
  119.    
  120.    
  121.     }  
  122.    
  123.     public String getXmlFromUrl(String url) {  
  124.         String xml = null;  
  125.    
  126.         try {  
  127.             // defaultHttpClient  
  128.             DefaultHttpClient httpClient = new DefaultHttpClient();  
  129.             HttpPost httpPost = new HttpPost(url);  
  130.    
  131.             HttpResponse httpResponse = httpClient.execute(httpPost);  
  132.             HttpEntity httpEntity = httpResponse.getEntity();  
  133.             xml = EntityUtils.toString(httpEntity);  
  134.    
  135.         } catch (UnsupportedEncodingException e) {  
  136.             e.printStackTrace();  
  137.         } catch (ClientProtocolException e) {  
  138.             e.printStackTrace();  
  139.         } catch (IOException e) {  
  140.             e.printStackTrace();  
  141.         }  
  142.         // return XML  
  143.         return xml;  
  144.     }  
  145.    
Step 3
 
Android Manifest.Xml file:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.xmlparsingdomparser"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   <uses-sdk  
  7.       android:minSdkVersion="7"  
  8.       android:targetSdkVersion="16" />  
  9.   <uses-permission android:name="android.permission.INTERNET"/>  
  10.   <application  
  11.       android:allowBackup="true"  
  12.       android:icon="@drawable/ic_launcher"  
  13.       android:label="@string/app_name"  
  14.       android:theme="@style/AppTheme" >  
  15.     <activity  
  16.         android:name="com.xmlparsingdomparser.MainActivity  
  17.   android:label="@string/app_name" >  
  18.       <intent-filter>  
  19.         <action android:name="android.intent.action.MAIN" />  
  20.  <category android:name="android.intent.category.LAUNCHER" />  
  21.       </intent-filter>  
  22.     </activity>  
  23.   </application>   
  24. </manifest> 
Step 4
 
Output
 
 
Progress.jpg
 
See the values in logcat:
 
LOGCAT.jpg