Android XML Parsing using SAX Parser

Using the SAX, DOM, etc., that are used as parsers, we can parse the XML file in Android. The SAX parser can be used to parse the XML file only and not to create the XML file.

Advantage of SAX Parser over DOM:

Compared to DOM, the SAX parser consumes less memory.

Example:

activity_main.xml:

In the activity_main.xml file, we will drag a Textview from the palette.

<?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" >
    <ListView
        android:id="@+id/user_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:dividerHeight="1dp" />
</LinearLayout>

List_row.xml:(File: list_row.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="5dip" >
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="17dp" />
    <TextView
        android:id="@+id/designation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_marginTop="7dp"
        android:textColor="#343434"
        android:textSize="14dp" />
    <TextView
        android:id="@+id/location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/designation"
        android:layout_alignBottom="@+id/designation"
        android:layout_alignParentRight="true"
        android:textColor="#343434"
        android:textSize="14dp" />
</RelativeLayout>

XML document: (File: userdetails.xml)

Inside the assets directory of the project, an XML file will be created.

<?xml version="1.0" encoding="utf-8"?>
 
<users>
 
    <user>
 
        <name>A</name>
 
        <designation>Leader</designation>
 
        <loation>City1</loation>
 
    </user>
 
    <user>
 
        <name>B</name>
 
        <designation>Secretary</designation>
 
        <loation>City2</loation>
 
    </user>
 
    <user>
 
        <name>C</name>
 
        <designation>Accountant</designation>
 
        <loation>City3</loation>
 
    </user>
 
    <user>
 
        <name>D</name>
 
        <designation>Officer 1</designation>
 
        <loation>City4</loation>
 
    </user>
 
    <user>
 
        <name>E</name>
 
        <designation>Officer 2</designation>
 
        <loation>City5</loation>
 
    </user>
 
</users>

Activity class:(File: MainActivity.java)

In the MainActivity.java file, we will write the code to parse the XML using the SAX parser.

package com.example.radioapp;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
 
public class MainActivity extends AppCompatActivity {
    ArrayList<HashMap<String, String>> userList = new ArrayList<>();
    HashMap<String,String> user = new HashMap<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try{
            ListView lv = (ListView) findViewById(R.id.user_list);
            SAXParserFactory parserFactory = SAXParserFactory.newInstance();
            SAXParser parser = parserFactory.newSAXParser();
            DefaultHandler handler = new DefaultHandler(){
                String currentValue = "";
                boolean currentElement = false;
                public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
                    currentElement = true;
                    currentValue = "";
                    if(localName.equals("user")){
                        user = new HashMap<>();
                    }
                }
                public void endElement(String uri, String localName, String qName) throws SAXException {
                    currentElement = false;
                    if (localName.equalsIgnoreCase("name"))
                        user.put("name", currentValue);
                    else if (localName.equalsIgnoreCase("designation"))
                        user.put("designation", currentValue);
                    else if (localName.equalsIgnoreCase("location"))
                        user.put("location", currentValue);
                    else if (localName.equalsIgnoreCase("user"))
                        userList.add(user);
                }
                @Override
                public void characters(char[] ch, int start, int length) throws SAXException {
                    if (currentElement) {
                        currentValue = currentValue +  new String(ch, start, length);
                    }
                }
            };
            InputStream istream = getAssets().open("userdetails.xml");
            parser.parse(istream,handler);
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, userList, R.layout.list_row,new String[]{"name","designation","location"}, new int[]{R.id.name, R.id.designation, R.id.location});
            lv.setAdapter(adapter);
        }
        catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }
}

Output:

Content Protection by DMCA.com
Please Share