XML Parsing Using SAX Parser

Android provides the facility to parse the xml file using different parsers such as SAX, DOM, etc. The SAX parser cannot be used to create the XML file, It can be used to parse the XML file only.

Parsing is an important part in any development cycle and so it is very important in android as well. Storing data on android device is not good and safe when you have a large amount of data. So we store the data on server and return it in XML format, then we parse it and show it on android device.

If you see SAX parser on wikipedia you will find below definition for it

“SAX (Simple API for XML) is an event-driven online algorithm for parsing XML documents, with an API interface developed by the XML-DEV mailing list. SAX provides a mechanism for reading data from an XML document that is an alternative to that provided by the Document Object Model (DOM).”

To parse the data using SAX you can create an InputStream either from a URL or from local file. In this tutorial we will store an xml file into assets and make an InputStream and parse it. Follow the steps below as given:

Step1: Create a new android project with name SAXxmlParsing.

Step2: Create an XML file named exampleXML.xml inside the assets directory and write the following into it:

 

<records>
<hotel>
<name>foodpanda</name>
<address>USA</address>
</hotel>
<hotel>
<name>Chipotle</name>
<address>Virginia</address>
</hotel>
<hotel>
<name>McDonald's</name>
<address>India</address>
</hotel>
</records>

 

 

Step3: Create a Textview in your main.xml as below to display the data fetched from xml:

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView android:text="Hotels of your Choice are:" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/textView1"/>

</RelativeLayout>

 

 

Step4: Write the following into your MainActivity.java:

 

package com.example.saxxmlparsing;

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 MainActivity extends Activity {
TextView tv;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
try {
SAXParserFactory factory = SAXParserFactory.newInstance();

SAXParser saxParser = factory.newSAXParser();

DefaultHandler handler = new DefaultHandler() {

boolean name = false;

boolean salary = false;

public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("name"))
{
name = true;
}
if (qName.equalsIgnoreCase("address"))
{
salary = true;
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
}

public void characters(char ch[], int start, int length) throws SAXException {
if (name) {

tv.setText(tv.getText()+"nn Hotel Name : " + new String(ch, start, length));
name = false;
}
if (salary) {
tv.setText(tv.getText()+"n Address : " + new String(ch, start, length));
salary = false;
}
}

};

InputStream is = getAssets().open("exampleXML.xml");
saxParser.parse(is, handler);

} catch (Exception e) {e.printStackTrace();}
}
}

 

 

And the output will display the list of hotels with address parsed from the xml file. as below:

sax1

You can store example XML file on server as well instead of assets folder. If you do so, you will need URL of the file to create InputStream object.

Check my post on Android XML Resources to read more on XML Pull Parser.

Leave a Comment: