Last Updated:

Parsing XML in Android with XMLPullParser

In this tutorial we will learn how to parse XML files using a simple Android application as an example. First, let's take a quick look at the XML processing capabilities in Java and look at the standard Android system tools for parsing XML.

XML Processing Tools in Java


Let's take a quick look at XML and existing tools. The word XML stands for Extensible Markup Language, which is used to create and conveniently process documentsThere are many tools and libraries for working with XML in Java. Let's look at some types of XML file parsers:

The DOM Parser uses the approach of parsing XML documents as a tree structure, where the entire XML file is validated and loaded into memory. Then the analysis of the document begins. Parsing occurs from the source node to the destination node. In general, this approach is slower than the next two.

The SAX parser is event-based: nothing is stored in memory, which improves performance. SAX starts the analysis from the top down and does not have the ability to disassemble individual nodes. XMLPullParser is very similar to SAX, but its advantage is that it can parse individual nodes.

Android uses XMLPullParser by default.

XMLPullParser example in Android

We will need any XML file with some content, for example:

We need to put this file in the folder . You need to create this folder in an Android Studio project and create a students.xml file with content like the one shown above:assets

Assets in Android Studio

The assets folder with the students file.xml

Now let's prepare a model that will represent information about one Student element:

Now let's look at the activity_main.xml layout file:

As you can see, it is quite simple and contains only one TextView widget inside the RelativeLayout component.

The next step is code to parse the XML file using the . Let's write it directly in MainActivity:XMLPullParser

Note! In the code above, we used the parser behavior modifier, which is this function that determines whether the namespace parser handles.parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);

Explanation of the code. As you can see from the code above, we go through a while loop through the file before the event that means the end of the file (). In each iteration, we've specified the events we need to handle (, etc.). We handle the events and store the values we need in the ArrayList. The result of the parse is printed in the widget.XmlPullParser.END_DOCUMENTXmlPullParser.START_TAGXmlPullParser.END_TAGTextView


The result of parsing the XML file using:XMLPullParser


Application screen with the results of parsing an XML file using XMLPullParser

Read more about XML processing in Java and Android.