XmlParsing Using XmlPullParser in Android Studio

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.    
  12.             android:id="@android:id/list"  
  13.    
  14.             android:layout_width="fill_parent"  
  15.    
  16.             android:layout_height="wrap_content"/>  
  17.    
  18. </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.    
  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.Element;  
  17. import org.w3c.dom.NodeList;  
  18. import org.xmlpull.v1.XmlPullParser;  
  19. import org.xmlpull.v1.XmlPullParserException;  
  20. import org.xmlpull.v1.XmlPullParserFactory;  
  21.    
  22. import java.io.IOException;  
  23. import java.io.StringReader;  
  24. import java.io.UnsupportedEncodingException;  
  25.    
  26. public class MainActivity extends ListActivity {  
  27.    
  28.     private static String BASE_URL = "http://maps.googleapis.com/maps/api/geocode/xml?address=NewDelhi&sensor=false";  
  29.    
  30.     @Override  
  31.     protected void onCreate(Bundle savedInstanceState) {  
  32.         super.onCreate(savedInstanceState);  
  33.         setContentView(R.layout.activity_main);  
  34.         (new ProgressTask(MainActivity.this)).execute();  
  35.     }  
  36. @Override  
  37.     public boolean onCreateOptionsMenu(Menu menu) {  
  38.         // Inflate the menu; this adds items to the action bar if it is present.  
  39.         getMenuInflater().inflate(R.menu.main, menu);  
  40.         return true;  
  41.     }  
  42.    
  43.     public class ProgressTask extends AsyncTask<String, Void, Boolean> {  
  44.    
  45.         private ProgressDialog dialog;  
  46.         private Context context;  
  47.    
  48.         public ProgressTask(ListActivity activity) {  
  49.             Log.i("1""Called");  
  50.             context = activity;  
  51.    
  52.             dialog = new ProgressDialog(context);  
  53.         }  
  54.         protected void onPreExecute() {  
  55.             this.dialog.setMessage("Progress start");  
  56.             this.dialog.show();  
  57.         }  
  58.         @Override  
  59.         protected void onPostExecute(final Boolean success) {  
  60.             if (dialog.isShowing()) {  
  61.                 dialog.dismiss();  
  62.             }  
  63.        }  
  64.          protected Boolean doInBackground(final String... args) {  
  65.             String xml = getXmlFromUrl(BASE_URL);  
  66.  //            useParserType1(xml);  
  67.             useParserType2(xml);  
  68.             return null;  
  69.        }  
  70.      }  
  71.   
  72.    //DOM Parser  
  73.     public void useParserType1(String xml){  
  74.         XmlParsingType1 parser = new XmlParsingType1();  
  75.         Document doc = parser.getDomElement(xml); // getting DOM element  
  76.    
  77.         NodeList GeocodeResponse = doc.getElementsByTagName("location");  
  78.    
  79.         for (int i = 0; i < GeocodeResponse.getLength(); i++) {  
  80.             Element e = (Element) GeocodeResponse.item(i);  
  81.             Log.i("xml", parser.getValue(e,"lat"));  
  82.             Log.i("xml", parser.getValue(e,"lng"));  
  83.         }  
  84.     }  
  85.    
  86.     //XmlPull Parser  
  87.     public void useParserType2(String xml){  
  88.         try{  
  89.         Boolean flagLocation = false;  
  90.         Boolean flagLatitude = false;  
  91.         Boolean flagLongitude = false;  
  92.         XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  
  93.         factory.setNamespaceAware(true);  
  94.         XmlPullParser xpp = factory.newPullParser();  
  95.    
  96.         xpp.setInput(new StringReader(xml));  
  97.         int eventType = xpp.getEventType();  
  98.         while (eventType != XmlPullParser.END_DOCUMENT) {  
  99.             if(eventType == XmlPullParser.START_DOCUMENT) {  
  100.    
  101.             } else if(eventType == XmlPullParser.END_DOCUMENT) {  
  102.    
  103.             } else if(eventType == XmlPullParser.START_TAG) {  
  104.    
  105.                 if (xpp.getName().equalsIgnoreCase("location")) flagLocation=true;  
  106.                 if (flagLocation && xpp.getName().equalsIgnoreCase("lat")) flagLatitude=true;  
  107.                 if (flagLocation && xpp.getName().equalsIgnoreCase("lng")) flagLongitude=true;  
  108.    
  109.             } else if(eventType == XmlPullParser.END_TAG) {  
  110.    
  111.                 if (xpp.getName().equalsIgnoreCase("location")) flagLocation=false;  
  112.                 if (flagLocation && xpp.getName().equalsIgnoreCase("lat")) flagLatitude=false;  
  113.                 if (flagLocation && xpp.getName().equalsIgnoreCase("lng")) flagLongitude=false;  
  114.    
  115.             } else if(eventType == XmlPullParser.TEXT) {  
  116.    
  117.    
  118.                 if (flagLatitude)  
  119.                     Log.i("Latitude: ", xpp.getText());  
  120.                 if (flagLongitude)  
  121.                     Log.i("Longitude: ", xpp.getText());  
  122.             }  
  123.             eventType = xpp.next();  
  124.         }  
  125.    
  126.         }catch (XmlPullParserException e){  
  127.             e.printStackTrace();  
  128.         }catch (IOException e){  
  129.             e.printStackTrace();  
  130.         }  
  131.     }  
  132.     public String getXmlFromUrl(String url) {  
  133.         String xml = null;  
  134.    
  135.         try {  
  136.             // defaultHttpClient  
  137.             DefaultHttpClient httpClient = new DefaultHttpClient();  
  138.             HttpPost httpPost = new HttpPost(url);  
  139.    
  140.             HttpResponse httpResponse = httpClient.execute(httpPost);  
  141.             HttpEntity httpEntity = httpResponse.getEntity();  
  142.             xml = EntityUtils.toString(httpEntity);  
  143.    
  144.         } catch (UnsupportedEncodingException e) {  
  145.             e.printStackTrace();  
  146.         } catch (ClientProtocolException e) {  
  147.             e.printStackTrace();  
  148.         } catch (IOException e) {  
  149.             e.printStackTrace();  
  150.         }  
  151.         // return XML  
  152.         return xml;  
  153.     }  
  154.      
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. /** 
  15.  * Created by naveen on 19/06/13. 
  16.  */  
  17. public class XmlParsingType1 {  
  18.    
  19.     public Document getDomElement(String xml){  
  20.         Document doc = null;  
  21.         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
  22.    
  23.         try {  
  24.    
  25.             DocumentBuilder db = dbf.newDocumentBuilder();  
  26.    
  27.             InputSource is = new InputSource();  
  28.             is.setCharacterStream(new StringReader(xml));  
  29.             doc = db.parse(is);  
  30.    
  31.         } catch (ParserConfigurationException e) {  
  32.             Log.e("Error: ", e.getMessage());  
  33.             return null;  
  34.         } catch (SAXException e) {  
  35.             Log.e("Error: ", e.getMessage());  
  36.             return null;  
  37.         } catch (IOException e) {  
  38.             Log.e("Error: ", e.getMessage());  
  39.             return null;  
  40.         }  
  41.         // return DOM  
  42.         return doc;  
  43.     }  
  44.    
  45.     public String getValue(Element item, String str) {  
  46.         NodeList n = item.getElementsByTagName(str);  
  47.         return this.getElementValue(n.item(0));  
  48.     }  
  49.    
  50.     public final String getElementValue( Node elem ) {  
  51.         Node child;  
  52.         if( elem != null){  
  53.             if (elem.hasChildNodes()){  
  54.                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){  
  55.                     if( child.getNodeType() == Node.TEXT_NODE  ){  
  56.                         return child.getNodeValue();  
  57.                     }  
  58.                 }  
  59.             }  
  60.         }  
  61.         return "";  
  62.     }  
Output
 
Clipboard03.jpg
 
See Logcat
 
Clipboard01.jpg