Android XML Parsing Using XMLPullParser

In this tutorial you will learn about android xml parsing using XMLPullParser.

XML is a popular and very commonly used format for sharing data on internet. In android there are several ways to parse xml data like DOM, SAX and XMLPullParser. But in this article I will teach you how to parse xml using XMLPullParser.

Android XML Parsing Using XMLPullParser

Steps for XML Parsing

XML parsing includes following steps.

1. First we have to read the xml file or data inside InputStream.

Here I have assumed that student.xml file is present in res/raw folder of project. You can also fetch the xml data from internet using url. The xml file contains data of students as shown below.

2. Create an instance of XMLPullParserFactory and using it call newPullParser() method to get instance of XMLPullParser.

3. Now provide InputStream object to XMLPullParser as an input using setInput() method.

4. Finally the data is read form XMLPullParser in following way.

The above code should be placed inside try-catch block.

The getEventType() method gives the type of event. It can be END_DOCUMENT, START_TAG, END_TAG, etc. On the basis of these events we filter and read the xml data.

The getName() method gives tag name while getText() method gives text information present inside that tag.

Android XMLPullParser Example

Below is a simple example that parses student data present in xml format using XMLPullParser.

1. Create a new android project with package name com.androidxmlparser.

2. Create a folder raw under res. Add a file student.xml inside res/raw with following xml data.

student.xml

3. By default you would get an activity MainActivity when you have created the project. This activity is used to display the parsed xml data. Just add following code inside its xml layout and java source file.

activity_main.xml

MainActivity.java

4. Now save and run the project. If everything was done correctly then you will see an output as shown in below image.

Screenshot

Android XML Parsing Using XMLPullParser

Comment below if you have doubts or found anything incorrect in above android xml parsing tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *