XML Parsing in Android using SAX Parser
Last Updated :
23 Feb, 2021
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:
- Prolog: The XML file will start with a prolog. Prolog contains the information about a file, which is available in the first line.
- Events: Events such as document start and end, tag start and end, etc. are contained in the XML file
- Text: It is a simple text present in between the opening and closing XML tag elements.
- 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?
- 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.
- We want to show this data in the form of a list to implement a ListView.
- 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().
- 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.
- Create an instance of SAXParserFactory, SAXParser, and DefaultHandler objects in android applications to read and parse the XML data using SAX parser in Android.
- 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.
Expand until you find the main folder, right-click on it, go to New > Folder > Assets Folder
Then just click on the Finish button.
Now the asset folder is created successfully. Right-Click on the Assets Folder > New > Android Resource FIle
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.
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
xmlns:android="http://schemas.android.com/apk/res/android"
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
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 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
Similar Reads
XML Parsing in Android using DOM Parser
Android DOM(Document Object Model) parser is a program that parses an XML document and extracts the required information from it. This parser uses an object-based approach for creating and parsing the XML files. In General, a DOM parser loads the XML file into the Android memory to parse the XML doc
6 min read
Processing and Parsing XML in Android
In this blog, we will learn about one of Android's most fascinating topics. Even most of us are unaware of it, despite the fact that it is one of the most essential ideas in Android development. But, before we get into our topic, take out your phones and count the number of apps you have on your sma
6 min read
JSON Parsing in Android using Volley Library
JSON is also known as (JavaScript Object Notation) is a format to exchange the data from the server. The data stored in JSON format is lightweight and easy to handle. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specif
6 min read
XML Parsing in Android using XmlPullParser
In android, the XMLPullParser interface provides the functionality to parse the XML files in android applications. The XMLPullParser is a simple and efficient parser method to parse the XML data when compared to other parser methods such as DOM Parser and SAX Parser. The XMLPullParser has a method n
5 min read
JSON Parsing in Android using Retrofit Library
JSON is also known as (JavaScript Object Notation) is a format to exchange the data from the server. The data stored in JSON format is lightweight and easy to handle. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specif
6 min read
JSON Parsing in Android
JSON (JavaScript Object Notation) is a straightforward data exchange format to interchange the server's data, and it is a better alternative for XML. This is because JSON is a lightweight and structured language. Android supports all the JSON classes such as JSONStringer, JSONObject, JSONArray, and
4 min read
What is Uri.parse() in Android?
Uri stands for Uniform Resource Identifier. Uri is the sequence of the characters used to identify resources uniquely over the internet. In this article, we are going to see what is Uri.parse() method in Android. Step-by-Step Implementation Step 1: Create a New Project in Android Studio To create a
2 min read
XML Namespaces in Android
In an XML file, namespaces are used to provide elements and attributes with distinctive names. Names for elements or attributes in an XML instance may come from different XML vocabularies. The ambiguity between similar elements or attributes can be eliminated if each vocabulary is given its own name
2 min read
Android - JSON Parsing using Retrofit Library with Kotlin
JSON is a format with the help of which we can exchange the data from the server within our application or a website. For accessing this data from the server within android applications. There are several libraries that are available such as Volley and Retrofit. In this article, we will take a look
6 min read
How to Send SMS in Android using Kotlin?
SMS Manager is a class in Android which is used to send the SMS to a specific contact from the android application. We can send text messages, data messages, and multimedia messages using this class. There are different methods that are provided to send different types of messages. In this article,
4 min read