Home » Kotlin Android XMLPullParser Tutorial

Kotlin Android XMLPullParser Tutorial

by Online Tutorials Library

Kotlin Android XMLPullParser Tutorial

XML document is commonly used to share the data on the internet. The data provided in XML format are able to update frequently and parsing them is a common task for network-based apps.

In android, there are three types of XML parsers to parse the XML data and read them in android applications.

These parsers are:

  1. DOM Parser
  2. SAX Parser
  3. XMLPullParser

Android recommends to use XMLPullParser to parse the XML file rather than SAX and DOM because it is fast.

The org.xmlpull.v1.XmlPullParser interface provides the functionality to parse the XML document using XMLPullParser.

Events of XmlPullParser

The next() method of XMLPullParser moves the cursor pointer to the next event. Generally, we use four constants (works as the event) defined in the XMLPullParser interface.

  1. START_TAG: An XML start tag will read.
  2. TEXT: Text content was read the text content can be retrieved using the getText() method.
  3. END_TAG: An end tag will read.
  4. END_DOCUMENT: No more events are available.

Example of XML Parsing using XMLPullParser

In this example, we read the XML data and bind them into a ListView using XMLPullParser.

activity_main.xml

Add the ListView in the activity_main.xml layout.

employees.xml

Create the XML document employees.xml in assets directory to parse the data using XMLPullParser.

Employee.kt

Create a data model class Employee.kt corresponds to the XML data file.

XmlPullParserHandler.kt

Write the code to parse the XML file using XMLPullParser. In this class, we return all the employees in the list.

MainActivity.kt

In this class, we send XML data into ArrayAdapter and bind them into ListView.

Output:

Kotlin Android XMLPullParser Tutorial

Next Topic#

You may also like