XML Parsing Using SAXparser in Android

Introduction

 
Hi friends. I am now showing you how to parse XML in Android using SAXParser.
 
XML is the simplest and easiest way to send data over the internet. When we are going to hit any HTTP request (make an HTTP connection to get data) we get the data in XML Format.
 
To parse the XML we have the XML data, make a new raw folder in the res folder in the Android application.
 
And make the XML file in it and paste the code given below.
  1. <dist>    
  2.    <item>    
  3.       <country>AFGHANISTAN</country>    
  4.          <alpha2>AF</alpha2>    
  5.          <alpha3>AFG</alpha3>    
  6.          <value>+93</value>    
  7.    </item>    
  8.    <item>    
  9.       <country>LAND ISLANDS</country>    
  10.       <alpha2>AX</alpha2>    
  11.       <alpha3>ALA</alpha3>    
  12.       <value>+248</value>    
  13.    </item>    
  14.    <item>    
  15.       <country>ALBANIA</country>    
  16.       <alpha2>AL</alpha2>    
  17.       <alpha3>ALB</alpha3>    
  18.       <value>+355</value>    
  19.    </item>    
  20.    <item>    
  21.       <country>ALGERIA</country>    
  22.       <alpha2>DZ</alpha2>    
  23.       <alpha3>DZA</alpha3>    
  24.       <value>+213</value>    
  25.    </item>    
  26.    <item>    
  27.       <country>AMERICAN SAMOA</country>    
  28.       <alpha2>AS</alpha2>    
  29.       <alpha3>ASM</alpha3>    
  30.       <value>+1684</value>    
  31.    </item>    
  32.    <item>    
  33.       <country>ANDORRA</country>    
  34.       <alpha2>AD</alpha2>    
  35.       <alpha3>AND</alpha3>    
  36.       <value>+376</value>    
  37.    </item>    
  38. </dist>   
The following is the Model class for the ArrayList:
  1. package com.ravi.model;    
  2. public class CountryCodeModel {    
  3.    String countryName;    
  4.    String countryCode;    
  5.    String countryShortCode;    
  6.    public String getCountryName() {    
  7.       return countryName;    
  8.    }    
  9.    public String getCountryCode() {    
  10.       return countryCode;    
  11.    }    
  12.    public String getCountryShortCode() {    
  13.       return countryShortCode;    
  14.    }    
  15.    public void setCountryName(String countryName) {    
  16.       this.countryName = countryName;    
  17.    }    
  18.    public void setCountryCode(String countryCode) {    
  19.       this.countryCode = countryCode;    
  20.    }    
  21.    public void setCountryShortCode(String countryShortCode) {    
  22.       this.countryShortCode = countryShortCode;    
  23.    }    
  24. }   
The following is the XMLHandler class that extends the DefaultHandler and overrides the three methods:
  1. public class XMLHandler extends DefaultHandler {    
  2.    boolean bCountryCode = false;    
  3.    boolean bCountryName = false;    
  4.    boolean bCountryShortCode = false;    
  5.    ArrayList<CountryCodeModel> countryCodeList = new ArrayList<CountryCodeModel>();    
  6.    private CountryCodeModel countryCode = null;    
  7.    public ArrayList<CountryCodeModel> getList() {    
  8.       return countryCodeList;    
  9.    }    
  10. }  
The override methods are the following:
  • @Override
    1. public void startElement(String uri, String localName, String qName,    
    2. Attributes attributes) throws SAXException {    
    3. }  
  • @Override
    1. public void endElement(String uri, String localName, String qName)    
    2. throws SAXException {    
    3. }   
  • @Override
    1. public void characters(char[] ch, int start, int length)    
    2. throws SAXException {    
    3. }   
    All these methods are useful for parsing the XML in the startElement method. We just check the tag name and make the boolean variable value true to make the Model class object useful in the characters method.
     
  • @Override
    1. public void startElement(String uri, String localName, String qName,    
    2. Attributes attributes) throws SAXException {    
    3.    if (qName.equalsIgnoreCase("value")) {    
    4.       bCountryCode = true;    
    5.    } else if (qName.equalsIgnoreCase("country")) {    
    6.       bCountryName = true;    
    7.       countryCode = new CountryCodeModel();    
    8.       } else if (qName.equalsIgnoreCase("alpha3")) {    
    9.       bCountryShortCode = true;    
    10.    }    
    11. }   
    Here the characters method code is given below.
     
  • @Override
    1. public void characters(char[] ch, int start, int length)    
    2. throws SAXException {    
    3.    if (bCountryCode) {    
    4.       bCountryCode = false;    
    5.       countryCode.setCountryCode(new String(ch, start, length));    
    6.    } else if (bCountryName) {    
    7.       bCountryName = false;    
    8.       countryCode.setCountryName(new String(ch, start, length));    
    9.    } else if (bCountryShortCode) {    
    10.       bCountryShortCode = false;    
    11.       countryCode.setCountryShortCode(new String(ch, start, length)); }    
    12. }   
    The EndElement method checks the last tag name. If they are there then add the model class object into the list.
     
  • @Override
    1. public void endElement(String uri, String localName, String qName)    
    2. throws SAXException {    
    3.    if (qName.equalsIgnoreCase("value")) {    
    4.       countryCodeList.add(countryCode);    
    5.    }    
    6. }   
    Now focus on the activity in which we write the code for parsing the XML. Make the oncreate method in the activity and make the SAXParserFactory object and also make the SAXParser object and make the XMLHandler class object.
     
  • @Override
    1. protected void onCreate(Bundle savedInstanceState) {    
    2.    super.onCreate(savedInstanceState);    
    3.    requestWindowFeature(Window.FEATURE_NO_TITLE);    
    4.    setContentView(R.layout.main_activity);    
    5.    ListView listView = (ListView) findViewById(R.id.listView);    
    6.    try {    
    7.       SAXParserFactory parserFactory = SAXParserFactory.newInstance();    
    8.       SAXParser parser = parserFactory.newSAXParser();    
    9.       XMLHandler handler = new XMLHandler();    
    10.       parser.parse(getResources()    
    11.       .openRawResource(R.raw.country_name_isd2), handler);    
    12.       countryCodeList = handler.getList();    
    13.    } catch (ParserConfigurationException e) {    
    14.    e.printStackTrace();    
    15.    } catch (SAXException e) {    
    16.       e.printStackTrace();    
    17.    } catch (NotFoundException e) {    
    18.       // TODO Auto-generated catch block    
    19.       e.printStackTrace();    
    20.    } catch (IOException e) {    
    21.       // TODO Auto-generated catch block    
    22.       e.printStackTrace();    
    23.    }    
    24.    CountryListAdapter adapter = new CountryListAdapter(    
    25.    MainHandlerActivity.this, countryCodeList);    
    26.    listView.setAdapter(adapter);    
    27. }  
    The last of the method adapter code is there, to just show the parse data in the List format.
     
    Now here is the complete code of the XMLHandler class and MainHandlerActiviy.
     
    XMLHandler.java
    1. package com.ravi.xmlhandler;    
    2. import java.util.ArrayList;    
    3. import org.xml.sax.Attributes;    
    4. import org.xml.sax.SAXException;    
    5. import org.xml.sax.helpers.DefaultHandler;    
    6. import com.ravi.model.CountryCodeModel;    
    7. /**  
    8. * @author ravi sharma  
    9.  
    10. */    
    11. public class XMLHandler extends DefaultHandler {    
    12.    boolean bCountryCode = false;    
    13.    boolean bCountryName = false;    
    14.    boolean bCountryShortCode = false;    
    15.    ArrayList<CountryCodeModel> countryCodeList = new ArrayList<CountryCodeModel>();    
    16.    private CountryCodeModel countryCode = null;    
    17.    public ArrayList<CountryCodeModel> getList() {    
    18.       return countryCodeList;    
    19.    }    
    20.    @Override    
    21.     
    22.    public void startElement(String uri, String localName, String qName,    
    23.    Attributes attributes) throws SAXException {    
    24.       if (qName.equalsIgnoreCase("value")) {    
    25.          bCountryCode = true;    
    26.          } else if (qName.equalsIgnoreCase("country")) {    
    27.          bCountryName = true;    
    28.          countryCode = new CountryCodeModel();    
    29.       } else if (qName.equalsIgnoreCase("alpha3")) {    
    30.       bCountryShortCode = true;    
    31.    }    
    32. }    
    33. @Override    
    34.     
    35. public void endElement(String uri, String localName, String qName)    
    36. throws SAXException {    
    37.    if (qName.equalsIgnoreCase("value")) {    
    38.       countryCodeList.add(countryCode);    
    39.       }    
    40.    }    
    41. @Override    
    42. public void characters(char[] ch, int start, int length)    
    43. throws SAXException {    
    44.    if (bCountryCode) {    
    45.       bCountryCode = false;    
    46.       countryCode.setCountryCode(new String(ch, start, length));    
    47.       } else if (bCountryName) {    
    48.          bCountryName = false;    
    49.          countryCode.setCountryName(new String(ch, start, length));    
    50.       } else if (bCountryShortCode) {    
    51.       bCountryShortCode = false;    
    52.       countryCode.setCountryShortCode(new String(ch, start, length)); }    
    53.    }    
    54. }  
    MainHandlerActivity.java
    1. package com.ravi.xmlhandler;    
    2. import java.io.IOException;    
    3. import java.util.ArrayList;    
    4. import javax.xml.parsers.ParserConfigurationException;    
    5. import javax.xml.parsers.SAXParser;    
    6. import javax.xml.parsers.SAXParserFactory;    
    7. import org.xml.sax.SAXException;    
    8. import com.example.xmlhandlerdemo.R;    
    9. import com.ravi.adapter.CountryListAdapter;    
    10. import com.ravi.model.CountryCodeModel;    
    11. import android.app.Activity;    
    12. import android.content.res.Resources.NotFoundException;    
    13. import android.os.Bundle;    
    14. import android.view.Window;    
    15. import android.widget.ListView;    
    16. public class MainHandlerActivity extends Activity {    
    17.    ArrayList<CountryCodeModel> countryCodeList = new ArrayList<CountryCodeModel>();    
    18.    @Override    
    19.    protected void onCreate(Bundle savedInstanceState) {    
    20.       super.onCreate(savedInstanceState);    
    21.       requestWindowFeature(Window.FEATURE_NO_TITLE);    
    22.       setContentView(R.layout.main_activity);    
    23.       ListView listView = (ListView) findViewById(R.id.listView);    
    24.       try {    
    25.          SAXParserFactory parserFactory = SAXParserFactory.newInstance();    
    26.          SAXParser parser = parserFactory.newSAXParser();    
    27.          XMLHandler handler = new XMLHandler();    
    28.          parser.parse(getResources()    
    29.          .openRawResource(R.raw.country_name_isd2), handler);    
    30.          countryCodeList = handler.getList();    
    31.       } catch (ParserConfigurationException e) {    
    32.         e.printStackTrace();    
    33.         } catch (SAXException e) {    
    34.          e.printStackTrace();    
    35.         } catch (NotFoundException e) {    
    36.          // TODO Auto-generated catch block    
    37.          e.printStackTrace();    
    38.          } catch (IOException e) {    
    39.          // TODO Auto-generated catch block    
    40.          e.printStackTrace();    
    41.       }    
    42.       CountryListAdapter adapter = new CountryListAdapter(    
    43.       MainHandlerActivity.this, countryCodeList);    
    44.       listView.setAdapter(adapter);    
    45.    }    
    46. }   
    Main_activity.xml
    1. <?xml version="1.0" encoding="utf-8"?>    
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    3.    android:layout_width="match_parent"    
    4.    android:layout_height="match_parent"    
    5.    android:orientation="vertical" >    
    6.    <ListView    
    7.       android:id="@+id/listView"    
    8.       android:layout_width="fill_parent"    
    9.       android:layout_height="fill_parent"    
    10.       android:divider="@android:color/black"    
    11.       android:dividerHeight="1dp" >    
    12.    </ListView>    
    13. </LinearLayout>   
    List_item.xml
    1. <?xml version="1.0" encoding="utf-8"?>    
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    3.    android:layout_width="match_parent"    
    4.    android:layout_height="match_parent"    
    5.    android:padding="5dp" >    
    6.    <TextView    
    7.       android:id="@+id/name"    
    8.       android:layout_width="wrap_content"    
    9.       android:layout_height="wrap_content"    
    10.       android:layout_alignParentLeft="true"    
    11.       android:layout_alignParentTop="true"    
    12.       android:padding="10dp"    
    13.       android:text="Country name"    
    14.       android:textColor="@android:color/black" />    
    15.    <TextView    
    16.       android:id="@+id/code"    
    17.       android:layout_width="wrap_content"    
    18.       android:layout_height="wrap_content"    
    19.       android:layout_alignParentRight="true"    
    20.       android:layout_alignParentTop="true"    
    21.       android:padding="10dp"    
    22.       android:text="Country Code"    
    23.       android:textColor="@android:color/black" />    
    24.    <TextView    
    25.       android:id="@+id/shortName"    
    26.       android:layout_width="wrap_content"    
    27.       android:layout_height="wrap_content"    
    28.       android:layout_alignParentLeft="true"    
    29.       android:layout_below="@id/name"    
    30.       android:layout_marginTop="5dp"    
    31.       android:padding="10dp"    
    32.       android:text="Short Name"    
    33.       android:textColor="@android:color/black" />    
    34. </RelativeLayout>  
The following is a snapshort of the result
 
XML


Similar Articles