Introduction

In this article, you will learn about XML parsing with the pull parser
XML Parsing
XML parsing is a process of converting data from a server in a machine-readable form.
XML pull parser
The XML pull parser is an interface that defines the parsing functionality. It provides two key methods next() that provide access to high-level parsing events. The current event state of the parser can be determined by the geteventType() method. Initially, the parser lies in the START_DOCUMENT state.
The following are the events seen by next():
  • START_TAG:
    an XML start tag was read.

  • Text:
    Text content was read. The text content was retrieved using the getText() method.

  • END_TAG:
    A tag was read.

  • END_DOCUMENT:
    No more events are available.
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
  11. android:id="@android:id/list"
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content"/>
  14. </RelativeLayout>
Step 2
Create a Java file MainActivity.java and write this:
  1. import android.app.ListActivity;
  2. import android.app.ProgressDialog;
  3. import android.content.Context;
  4. import android.os.AsyncTask;
  5. import android.os.Bundle;
  6. import android.util.Log;
  7. import android.view.Menu;
  8. import org.apache.http.HttpEntity;
  9. import org.apache.http.HttpResponse;
  10. import org.apache.http.client.ClientProtocolException;
  11. import org.apache.http.client.methods.HttpPost;
  12. import org.apache.http.impl.client.DefaultHttpClient;
  13. import org.apache.http.util.EntityUtils;
  14. import org.w3c.dom.Document;
  15. import org.w3c.dom.Element;
  16. import org.w3c.dom.NodeList;
  17. import org.xmlpull.v1.XmlPullParser;
  18. import org.xmlpull.v1.XmlPullParserException;
  19. import org.xmlpull.v1.XmlPullParserFactory;
  20. import java.io.IOException;
  21. import java.io.StringReader;
  22. import java.io.UnsupportedEncodingException;
  23. public class MainActivity extends ListActivity {
  24. private static String BASE_URL = "http://maps.googleapis.com/maps/api/geocode/xml?address=NewDelhi&sensor=false";
  25. @Override
  26. protected void onCreate(Bundle savedInstanceState) {
  27. super.onCreate(savedInstanceState);
  28. setContentView(R.layout.activity_main);
  29. (new ProgressTask(MainActivity.this)).execute();
  30. }
  31. @Override
  32. public boolean onCreateOptionsMenu(Menu menu) {
  33. // Inflate the menu; this adds items to the action bar if it is present.
  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. // useParserType1(xml);
  58. useParserType2(xml);
  59. return null;
  60. }
  61. }
  62. //DOM Parser
  63. public void useParserType1(String xml){
  64. XmlParsingType1 parser = new XmlParsingType1();
  65. Document doc = parser.getDomElement(xml); // getting DOM element
  66. NodeList GeocodeResponse = doc.getElementsByTagName("location");
  67. for (int i = 0; i < GeocodeResponse.getLength(); i++) {
  68. Element e = (Element) GeocodeResponse.item(i);
  69. Log.i("xml", parser.getValue(e,"lat"));
  70. Log.i("xml", parser.getValue(e,"lng"));
  71. }
  72. }
  73. //XmlPull Parser
  74. public void useParserType2(String xml){
  75. try{
  76. Boolean flagLocation = false;
  77. Boolean flagLatitude = false;
  78. Boolean flagLongitude = false;
  79. XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
  80. factory.setNamespaceAware(true);
  81. XmlPullParser xpp = factory.newPullParser();
  82. xpp.setInput(new StringReader(xml));
  83. int eventType = xpp.getEventType();
  84. while (eventType != XmlPullParser.END_DOCUMENT) {
  85. if(eventType == XmlPullParser.START_DOCUMENT) {
  86. } else if(eventType == XmlPullParser.END_DOCUMENT) {
  87. } else if(eventType == XmlPullParser.START_TAG) {
  88. if (xpp.getName().equalsIgnoreCase("location")) flagLocation=true;
  89. if (flagLocation && xpp.getName().equalsIgnoreCase("lat")) flagLatitude=true;
  90. if (flagLocation && xpp.getName().equalsIgnoreCase("lng")) flagLongitude=true;
  91. } else if(eventType == XmlPullParser.END_TAG) {
  92. if (xpp.getName().equalsIgnoreCase("location")) flagLocation=false;
  93. if (flagLocation && xpp.getName().equalsIgnoreCase("lat")) flagLatitude=false;
  94. if (flagLocation && xpp.getName().equalsIgnoreCase("lng")) flagLongitude=false;
  95. } else if(eventType == XmlPullParser.TEXT) {
  96. if (flagLatitude)
  97. Log.i("Latitude: ", xpp.getText());
  98. if (flagLongitude)
  99. Log.i("Longitude: ", xpp.getText());
  100. }
  101. eventType = xpp.next();
  102. }
  103. }catch (XmlPullParserException e){
  104. e.printStackTrace();
  105. }catch (IOException e){
  106. e.printStackTrace();
  107. }
  108. }
  109. public String getXmlFromUrl(String url) {
  110. String xml = null;
  111. try {
  112. // defaultHttpClient
  113. DefaultHttpClient httpClient = new DefaultHttpClient();
  114. HttpPost httpPost = new HttpPost(url);
  115. HttpResponse httpResponse = httpClient.execute(httpPost);
  116. HttpEntity httpEntity = httpResponse.getEntity();
  117. xml = EntityUtils.toString(httpEntity);
  118. } catch (UnsupportedEncodingException e) {
  119. e.printStackTrace();
  120. } catch (ClientProtocolException e) {
  121. e.printStackTrace();
  122. } catch (IOException e) {
  123. e.printStackTrace();
  124. }
  125. // return XML
  126. return xml;
  127. }
  128. }
Step 3
Create another Java class file XMLParser.java and write this:
  1. import android.util.Log;
  2. import org.w3c.dom.Document;
  3. import org.w3c.dom.Element;
  4. import org.w3c.dom.Node;
  5. import org.w3c.dom.NodeList;
  6. import org.xml.sax.InputSource;
  7. import org.xml.sax.SAXException;
  8. import java.io.IOException;
  9. import java.io.StringReader;
  10. import javax.xml.parsers.DocumentBuilder;
  11. import javax.xml.parsers.DocumentBuilderFactory;
  12. import javax.xml.parsers.ParserConfigurationException;
  13. /**
  14. * Created by naveen on 19/06/13.
  15. */
  16. public class XmlParsingType1 {
  17. public Document getDomElement(String xml){
  18. Document doc = null;
  19. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  20. try {
  21. DocumentBuilder db = dbf.newDocumentBuilder();
  22. InputSource is = new InputSource();
  23. is.setCharacterStream(new StringReader(xml));
  24. doc = db.parse(is);
  25. } catch (ParserConfigurationException e) {
  26. Log.e("Error: ", e.getMessage());
  27. return null;
  28. } catch (SAXException e) {
  29. Log.e("Error: ", e.getMessage());
  30. return null;
  31. } catch (IOException e) {
  32. Log.e("Error: ", e.getMessage());
  33. return null;
  34. }
  35. // return DOM
  36. return doc;
  37. }
  38. public String getValue(Element item, String str) {
  39. NodeList n = item.getElementsByTagName(str);
  40. return this.getElementValue(n.item(0));
  41. }
  42. public final String getElementValue( Node elem ) {
  43. Node child;
  44. if( elem != null){
  45. if (elem.hasChildNodes()){
  46. for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
  47. if( child.getNodeType() == Node.TEXT_NODE ){
  48. return child.getNodeValue();
  49. }
  50. }
  51. }
  52. }
  53. return "";
  54. }
  55. }
Output
Clipboard03.jpg
See Logcat
Clipboard01.jpg