Open In App

XML Parsing in Android using SAX Parser

Last Updated : 23 Feb, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Generally, XML (Extensible Mark-up Language) is a commonly used data exchange format to interchange servers’ data. In Android, SAX stands for Simple API for XML and is a widely used API for XML parsing. Like the DOM parser, the SAX parser is also used to perform in-memory operations to parse the XML document, but it consumes less memory than the DOM parser. The main advantage of a SAX parser over a DOM parser is that one can instruct the SAX parser to stop midway through a document without losing any collected data. The XML file that contains the information to be extracted includes the following four main components:

  1. Prolog: The XML file will start with a prolog. Prolog contains the information about a file, which is available in the first line.
  2. Events: Events such as document start and end, tag start and end, etc. are contained in the XML file
  3. Text: It is a simple text present in between the opening and closing XML tag elements.
  4. Attributes: They are the additional properties of a tag present within the label.

Note that we are going to implement this project using the Kotlin language. One may also perform XML Parsing in another two ways. Please refer to the below articles:

What we are going to do?

  1. We need to have an XML file with some information so that we would make one. Place this file under the assets folder. This file is called and would be parsed.
  2. We want to show this data in the form of a list to implement a ListView.
  3. SAX parser scrutinizes an XML file character by character, and translates the XML file into a series of events, such as startElement(), endElement() and characters().
  4. A ContentHandler object will process these events to perform the appropriate action. The parse() method will send the events to the content object to deals with them.
  5. Create an instance of SAXParserFactory, SAXParser, and DefaultHandler objects in android applications to read and parse the XML data using SAX parser in Android.
  6. Using a ListAdapter, the data is sent to the ListView where it is displayed on the screen.

Approach

To parse an XML file using a SAX parser in Android, follow the following steps:

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Create an assets folder

Create an assets folder under the main folder in the Project Layout. Create an Android Resource File in this folder, where we shall put the information in the form of XML. Name this file as userdetails.xml. For doing so refer to the following steps:

Click on Project as shown on the left side of the below image. 

Click on project

Expand until you find the main folder, right-click on it, go to New > Folder > Assets Folder

Asset folder

Then just click on the Finish button.

asset folder

Now the asset folder is created successfully. Right-Click on the Assets Folder > New > Android Resource FIle 

asset folder

Give it name Information, change type to XML, and finish.

Note: Sometimes, right-clicking on the Assets folder and creating an Android Resource File creates a file in the res folder. If this happens, cut our file and paste it directly into the assets folder. This happens due to some internal settings.

asset folder

Paste this information which is in the form of XML, that is to be displayed in the userdetails.xml file. Below is the code for the userdetails.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<users>
    <user>
        <name>Satya</name>
        <designation>CTO</designation>
    </user>
    <user>
        <name>Ajaypal</name>
        <designation>CEO</designation>
    </user>
    <user>
        <name>Mark</name>
        <designation>Consultant</designation>
    </user>
</users>


Step 3: Working with the activity_main.xml file

Now go to the activity_main.xml file which represents the UI of the application. Create a ListView as shown. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
  
    <!--A list View that will show the list elements-->
    <ListView
        android:id="@+id/user_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:dividerHeight="1dp" />
</LinearLayout>


Step 4: Create another layout file

Go to app > res > layout > right-click > New > Layout Resource File and name the file as list. list.xml file is used to show the data in the ListView. Below is the code for the list.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="5dip">
  
    <!--TextView to show the user name-->
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="17dp"
        android:textStyle="bold" />
  
    <!--TextView to show the user designation-->
    <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" />
  
</RelativeLayout>


Step 5: Working with the MainActivity.kt file

Finally, go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




import android.os.Bundle
import android.view.View
import android.widget.ListAdapter
import android.widget.ListView
import android.widget.SimpleAdapter
import androidx.appcompat.app.AppCompatActivity
import org.xml.sax.Attributes
import org.xml.sax.SAXException
import org.xml.sax.helpers.DefaultHandler
import java.io.IOException
import java.util.*
import javax.xml.parsers.ParserConfigurationException
import javax.xml.parsers.SAXParserFactory
  
class MainActivity : AppCompatActivity() {
  
    // Create a userlist
    var userList = ArrayList<HashMap<String, String?>>()
  
    // create a user hashmap
    var user = HashMap<String, String?>()
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        try {
  
            // Declare the list view from the layout file
            val lv = findViewById<View>(R.id.user_list) as ListView
  
            // Creating and initializing an instance of SAX parser factory
            val parserFactory = SAXParserFactory.newInstance()
            val parser = parserFactory.newSAXParser()
  
            // Default handler
            val handler: DefaultHandler = object : DefaultHandler() {
                var currentValue = ""
                var currentElement = false
  
                // Start element function
                @Throws(SAXException::class)
                override fun startElement(
                    uri: String,
                    localName: String,
                    qName: String,
                    attributes: Attributes
                ) {
                    currentElement = true
                    currentValue = ""
                    if (localName == "user") {
                        user = HashMap()
                    }
                }
  
                // End element function
                @Throws(SAXException::class)
                override fun endElement(uri: String, localName: String, qName: String) {
                    currentElement = false
                    when {
                        localName.equals("name", ignoreCase = true) -> user["name"] = currentValue
                        localName.equals("designation", ignoreCase = true) -> user["designation"] = currentValue
                        localName.equals("user", ignoreCase = true) -> userList.add(user)
                    }
                }
  
                // characters function
                @Throws(SAXException::class)
                override fun characters(ch: CharArray, start: Int, length: Int) {
                    if (currentElement) {
                        currentValue += String(ch, start, length)
                    }
                }
            }
  
            // Feeding the userdetails.xml file as an Input stream
            val iStream = assets.open("userdetails.xml")
            parser.parse(iStream, handler)
  
            // Adapter to broadcast the information to the list
            val adapter: ListAdapter = SimpleAdapter(this, userList, R.layout.list,
                arrayOf("name", "designation"), intArrayOf(R.id.name, R.id.designation)
            )
            lv.adapter = adapter
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: ParserConfigurationException) {
            e.printStackTrace()
        } catch (e: SAXException) {
            e.printStackTrace()
        }
    }
}


Output: Run on Emulator

Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads