XML Parsing in Android using XmlPullParser
Last Updated :
23 Feb, 2021
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 next() that provides access to high-level parsing events. The next() method will advance the parser to the next event. The following are the series of events available in XMLPullParser, which will be seen by the next() method.
- START_DOCUMENT: The parser starts processing the XML document.
- START_TAG: In this event, we can get the start tag in XML.
- TEXT: In this event, we can read the text content using the getText() method.
- END_TAG: An end tag was read.
- END_DOCUMENT: No more events are available.
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?
XMLPullParser scrutinizes an XML file with a series of events, such as START_DOCUMENT, START_TAG, TEXT, END_TAG, and END_DOCUMENT to parse the XML document. To read and parse XML files using XMLPullParser in android, one needs to create an instance of XMLPullParserFactory, and XMLPullParser.
Approach
To parse an XML file using a DOM parser in Android, we 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>Tom</name>
<designation>Actor and Producer</designation>
</user>
<user>
<name>Danny</name>
<designation>Music Director</designation>
</user>
<user>
<name>Christopher</name>
<designation>Writer</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" >
<!--Display the list from list_row file-->
<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_row. list_row.xml file is used to show the data in the ListView. Below is the code for the list_row.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 display the name
from the userdetails file-->
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:textStyle="bold" />
<!--TextView to display the designation
from the userdetails file-->
<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.widget.ListAdapter
import android.widget.ListView
import android.widget.SimpleAdapter
import androidx.appcompat.app.AppCompatActivity
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import org.xmlpull.v1.XmlPullParserFactory
import java.io.IOException
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
try {
// creating a user list string hash map arraylist
val userList = ArrayList<HashMap<String, String?>>()
// creating a user string hashmap
var user = HashMap<String, String?>()
// declaring the list view from the layout file
val lv = findViewById<ListView>(R.id.user_list)
// input stream the userdetails.xml file
val istream = assets.open("userdetails.xml")
//creating a XmlPull parse Factory instance
val parserFactory = XmlPullParserFactory.newInstance()
val parser = parserFactory.newPullParser()
// setting the namespaces feature to false
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
// setting the input to the parser
parser.setInput(istream, null)
// working with the input stream
var tag: String? = ""
var text: String? = ""
var event = parser.eventType
while (event != XmlPullParser.END_DOCUMENT) {
tag = parser.name
when (event) {
XmlPullParser.START_TAG -> if (tag == "user") user = HashMap()
XmlPullParser.TEXT -> text = parser.text
XmlPullParser.END_TAG -> when (tag) {
"name" -> user["name"] = text
"designation" -> user["designation"] = text
"user" -> userList.add(user)
}
}
event = parser.next()
}
// List Adapter to broadcast the information to the list_rows.xml file
val adapter: ListAdapter = SimpleAdapter(this, userList, R.layout.list_row,
arrayOf("name", "designation"), intArrayOf(R.id.name, R.id.designation)
)
lv.adapter = adapter
} catch (e: IOException) {
e.printStackTrace()
} catch (e: XmlPullParserException) {
e.printStackTrace()
}
}
}
Output: Run on Emulator
Similar Reads
XML Parsing in Android using SAX Parser
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
6 min read
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
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
JSON Parsing in Android Using Volley Library with Kotlin
JSON is a JavaScript object notation which is a format to exchange the data from the server. JSON stores the data in a lightweight format. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the im
5 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
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
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
Synthetic Binding in Android
In android application development, for every view in the XML, we need to get an instance of that view to get access to it for doing any operation on it, like changing any property of a view. This is a very common requirement in any android application development cycle. There are main two ways of a
3 min read