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. </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. public class MainActivity extends ListActivity {
  25. private static String BASE_URL = "http://maps.googleapis.com/maps/api/geocode/xml?address=NewDelhi&sensor=false";
  26. @Override
  27. protected void onCreate(Bundle savedInstanceState) {
  28. super.onCreate(savedInstanceState);
  29. setContentView(R.layout.activity_main);
  30. (new ProgressTask(MainActivity.this)).execute();
  31. }
  32. @Override
  33. public boolean onCreateOptionsMenu(Menu menu) {
  34. getMenuInflater().inflate(R.menu.main, menu);
  35. return true;
  36. }
  37. public class ProgressTask extends AsyncTask<String, Void, Boolean> {
  38. private ProgressDialog dialog;
  39. private Context context;
  40. public ProgressTask(ListActivity activity) {
  41. Log.i("1", "Called");
  42. context = activity;
  43. dialog = new ProgressDialog(context);
  44. }
  45. protected void onPreExecute() {
  46. this.dialog.setMessage("Progress start");
  47. this.dialog.show();
  48. }
  49. @Override
  50. protected void onPostExecute(final Boolean success) {
  51. if (dialog.isShowing()) {
  52. dialog.dismiss();
  53. }
  54. }
  55. protected Boolean doInBackground(final String... args) {
  56. String xml = getXmlFromUrl(BASE_URL);
  57. userParserType2(xml);
  58. return null;
  59. }
  60. public void userParserType2 (String xml){
  61. try {
  62. DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
  63. DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
  64. Document doc = docBuilder.parse (xml);
  65. // normalize text representation
  66. System.out.println("firt:-"+doc.getDocumentElement ().getNodeName());
  67. NodeList listOfObject = doc.getDocumentElement().getChildNodes();
  68. for(int i=0;i<listOfObject.getLength();i++)
  69. {
  70. if(listOfObject.item(i).getFirstChild()!=null&&listOfObject.item(i).getNodeName().equals("result"))
  71. {
  72. NodeList listOfResultChild=listOfObject.item(i).getChildNodes();
  73. for(int j=0;j<listOfResultChild.getLength();j++)
  74. {
  75. if(listOfResultChild.item(j).getFirstChild()!=null&&listOfResultChild.item(j).getNodeName().equals("geometry"))
  76. {
  77. Node geometry=listOfResultChild.item(j);
  78. NodeList geometryList=geometry.getChildNodes();
  79. for(int k=0;k<geometryList.getLength();k++)
  80. {
  81. if(geometryList.item(k).getFirstChild()!=null&&geometryList.item(k).getNodeName().equals("location"))
  82. {
  83. NodeList locationList=geometryList.item(k).getChildNodes();
  84. for(int l=0;l<locationList.getLength();l++)
  85. {
  86. if(locationList.item(l).getFirstChild()!=null)
  87. {
  88. System.out.println(locationList.item(l).getNodeName());
  89. System.out.println(locationList.item(l).getTextContent());
  90. }
  91. }
  92. }
  93. }
  94. }
  95. }
  96. }
  97. }
  98. }catch (SAXParseException err) {
  99. System.out.println ("** Parsing error" + ", line "
  100. + err.getLineNumber () + ", uri " + err.getSystemId ());
  101. System.out.println(" " + err.getMessage ());
  102. }catch (SAXException e) {
  103. Exception x = e.getException ();
  104. ((x == null) ? e : x).printStackTrace ();
  105. }catch (Throwable t) {
  106. t.printStackTrace ();
  107. }
  108. //System.exit (0);
  109. }//end of main
  110. }
  111. public String getXmlFromUrl(String url) {
  112. String xml = null;
  113. try {
  114. // defaultHttpClient
  115. DefaultHttpClient httpClient = new DefaultHttpClient();
  116. HttpPost httpPost = new HttpPost(url);
  117. HttpResponse httpResponse = httpClient.execute(httpPost);
  118. HttpEntity httpEntity = httpResponse.getEntity();
  119. xml = EntityUtils.toString(httpEntity);
  120. } catch (UnsupportedEncodingException e) {
  121. e.printStackTrace();
  122. } catch (ClientProtocolException e) {
  123. e.printStackTrace();
  124. } catch (IOException e) {
  125. e.printStackTrace();
  126. }
  127. // return XML
  128. return xml;
  129. }
  130. }
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