Android SAX Parser Example


In this example we will see how to parse an XML file using SAX Parser in Android. What we do here is load the .xml file in the assets folder and parse the content inside and show them in a text view.

To do parsing we use the following callback methods :
  • startDocument() and endDocument() is called at the start and end of the document.
  • startElement() and endElement() is called at the start and end of the element.
  • characters() is called with the text contents between the element.
So let us start:

1.Create an xml file (file.xml) like below

file.xml

<?xml version="1.0"?>
<contacts>
<contact>
<firstname>Sachin</firstname>
<lastname>Tendulkar</lastname>
<email>sachin@xyz.com</email>
<phone>9999999999</phone>
</contact>
<contact>
<firstname>Brain</firstname>
<lastname>Lara</lastname>
<email>lara@xyz.com</email>
<phone>9999999999</phone>
</contact>
<contact>
<firstname>Steve</firstname>
<lastname>Waugh</lastname>
<email>steve@xyz.com</email>
<phone>9999999999</phone>
</contact>
</contacts>
2. Create a new project File ->New -> Project ->Android ->Android Application Project. While creating a new project give activity name as SAXParserActivity(SAXParserActivity.java). Copy and paste the xml file inside the assets folder of the android project. In the activity we parse the xml file using the org.xml.sax.helpers.DefaultHandler.

SAXParserActivity.java:
import java.io.InputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SAXParserActivity extends Activity {
 TextView tv;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  tv = (TextView) findViewById(R.id.textView1);
  try {
   SAXParserFactory factory = SAXParserFactory.newInstance();
   SAXParser saxParser = factory.newSAXParser();
   DefaultHandler handler = new DefaultHandler() {
    boolean bfname = false;
    boolean blname = false;
    boolean bemail = false;
    boolean bphone = false;

    public void startElement(String uri, String localName,
      String qName, Attributes attributes)
      throws SAXException {
     if (qName.equalsIgnoreCase("FIRSTNAME")) {
      bfname = true;
     }
     if (qName.equalsIgnoreCase("LASTNAME")) {
      blname = true;
     }
     if (qName.equalsIgnoreCase("EMAIL")) {
      bemail = true;
     }
     if (qName.equalsIgnoreCase("PHONE")) {
      bphone = true;
     }
    }

    public void endElement(String uri, String localName,
      String qName) throws SAXException {
    }

    public void characters(char ch[], int start, int length)
      throws SAXException {
     if (bfname) {
      tv.setText(tv.getText() + "\n\n First Name : "
        + new String(ch, start, length));
      bfname = false;
     }
     if (blname) {
      tv.setText(tv.getText() + "\n Last Name : "
        + new String(ch, start, length));
      blname = false;
     }
     if (bemail) {
      tv.setText(tv.getText() + "\n Email : "
        + new String(ch, start, length));
      bemail = false;
     }
     if (bphone) {
      tv.setText(tv.getText() + "\n Phone : "
        + new String(ch, start, length));
      bphone = false;
     }
    }
   };
   InputStream is = this.getAssets().open("file.xml");
   saxParser.parse(is, handler);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
3. Now in the main.xml, add the id attribute for the TextView to be used in the SAXParserActivity


main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="SAX Parser Example" />

</LinearLayout>
4.Run the project by rightclicking project Run as → android project. This project is tested with amdroid API level 8

Output:

The output of this example would be similar to the one as follows: