Android Parsing Local Xml File and Parsing Remote XML file Examples in Android

In this tutorial, we are going to learn how to parse local xml file stored in our project assets folder. After then, we will move further to see how we can parse a remote xml file using the url.

Xml is a human like language that is platform independent. It is use to exchange data between two different technologies.

Some third-party applications expose their data access through xml consumption. Although Json is becoming more popular this days but there are many technologies and systems that depends on xml format.

Android has different built-in xml parsers which you can employ in your application to parse your xml content. They are SAX, DOM and XMLPullParser.

Among all the options, it is recommended to use XmlPullParser class in android.

If you are looking for a way to parse Json object in android, I wrote a tutorial on it. I will suggest your take out time and read the tutorial here – How to Parse JSON in Android Example. You can also have a look at this tutorial if you want to use Gson library to parse your Json file – Android Json parsing with Gson

Now let focus on the application we will write. The application will have a simple UI. We will add a Button and TextView widgets in our layout file,

The button will have a click event attached to it so when it is clicked, the app will read the xml file which we will store in the assets folder in our project.

If your project does not contain any assets folder, create one folder and put it inside the app folder.

Before we start, it is important for you to understand the tools and environment I used in this android tutorial. Feel free to use tools you are familiar with.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidXmlParser

Package: com.inducesmile.androidxmlparser

Select Blank Activity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

If you are using Android Studio as your choice IDE, the new project will create a default MainActivity.java and its corresponding layout file activity_main/xml.

Before we start working with these file, lets save the xml file we will read in the assets folder.

Create a file and name it parse.xml. Put this file inside the assets folder. Copy and paste the code below inside the file.

Parse.xml

<?xml version="1.0" encoding="utf-8"?>
<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>

The content of the file is small but the same mechanism is applied when the content is big. Our focus will be to get all the information present in the note root element.

There is so much to learn about XML. If you are interested in learning more about XML, you can find different information on the topic here.

activity_main.xml

Open the activity_main.xml layout file. Copy and paste the code below inside the file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.inducesmile.androidxmlparser.MainActivity">
    <TextView
        android:id="@+id/display_xml"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="18sp" />
    <Button
        android:id="@+id/load_xml_file"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/display_xml"
        android:layout_centerHorizontal="true"
        android:text="@string/parse_xml"
        android:textAllCaps="false"
        android:padding="24dp"
        android:layout_marginTop="24dp"/>
    <Button
        android:id="@+id/navigate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/load_xml_file"
        android:layout_centerHorizontal="true"
        android:text="@string/navigate"
        android:textAllCaps="false"
        android:padding="24dp"
        android:layout_marginTop="24dp"/>
</RelativeLayout>

You can see that the layout file is very simple and need know explaination. Next, we will move over to the MainActivity.java.

Open the MainActivity.java file, we will get the instance of the View controls and wire click event to the buttons.

The second button when click will lead to the ParseActivity page. We will talk about that page when we are done with this.

Copy and paste the below code inside this file.

MainActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
    private TextView displayXmlContent;
    private XmlPullParserFactory xmlPullParserFactory;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        displayXmlContent = (TextView)findViewById(R.id.display_xml);
        Button navigate = (Button)findViewById(R.id.navigate);
        navigate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ParseXmlActivity.class);
                startActivity(intent);
            }
        });
        Button loadXmlButton = (Button)findViewById(R.id.load_xml_file);
        loadXmlButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    xmlPullParserFactory = XmlPullParserFactory.newInstance();
                    xmlPullParserFactory.setNamespaceAware(false);
                    XmlPullParser parser = xmlPullParserFactory.newPullParser();
                    // access the xml file and convert it to input stream
                    InputStream is = returnXmlInputStream();
                    parser.setInput(is, null);
                    String returnedStringValue = getLoadedXmlValues(parser);
                    displayXmlContent.setText(returnedStringValue);
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private InputStream returnXmlInputStream() throws IOException {
        InputStream is = this.getAssets().open("parse.xml");
        return is;
    }
    private String getLoadedXmlValues(XmlPullParser parser) throws XmlPullParserException, IOException {
        int eventType = parser.getEventType();
        String name = null;
        Entity mEntity = new Entity();
        while (eventType != XmlPullParser.END_DOCUMENT){
            if(eventType == XmlPullParser.START_TAG){
                name = parser.getName();
                if(name.equals("to")){
                    mEntity.to = parser.nextText();
                }
                else if(name.equals("from")){
                    mEntity.fromm = parser.nextText();
                }
                else if(name.equals("heading")){
                    mEntity.heading = parser.nextText();
                }
                else if(name.equals("body")){
                    mEntity.body = parser.nextText();
                }
            }
            eventType = parser.next();
        }
        return mEntity.to + ", " + mEntity.fromm + ", " + mEntity.heading + ", " + mEntity.body;
    }
    public class Entity{
        public String to;
        public String fromm;
        public String heading;
        public String body;
    }
}

We used this method XmlPullParserFactory.newInstance()to create an XmlPullParserFactory instance and for the parser object, we will call this method xmlPullParserFactory.newPullParser().

We will create two private methods returnXmlInputStream() and getLoadedXmlValues(XmlPullParser parser) respectively. The first method returns inputStream while the second extract the Note information from the xml.

You can run the application and see the result for yourself. Now, lets move over to the second Activity class which we will use to download a remote xml content inside our app.

Create a new Activity file by following the same method we used above to create our first Activity page.

Name the Activity file ParseXmlActivity.java. Open the activity layout, copy and paste the following code.

activity_parse_xml.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.inducesmile.androidxmlparser.ParseXmlActivity">
    <TextView
        android:id="@+id/display_xml"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="18sp" />
    <Button
        android:id="@+id/load_xml_file"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/display_xml"
        android:layout_centerHorizontal="true"
        android:text="@string/parse_xml"
        android:textAllCaps="false"
        android:padding="24dp"
        android:layout_marginTop="24dp"/>
</RelativeLayout>

This layout file is almost similar to the initial layout file. It contains a Button and TextView widget.

For the ParseXmlActivity.java, it will more or less look similar to the MainActivity class. Since we are downloading and parsing the xml file a remote server, we will provide the path to the remote xml.

Open the Manifest.xml file of your project and add Internet permission. This is important since will are making remote call over internet.

<uses-permission android:name="android.permission.INTERNET" />

Secondly, we will create an AsyncTask inner class to run our remote call in background so that it will not interfere or cause the UI Thread to force-close our application.

Copy and paste the code below to your activity file.

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ParseXmlActivity extends AppCompatActivity {
    protected TextView displayXmlContent;
    protected XmlPullParserFactory xmlPullParserFactory;
    protected XmlPullParser parser;
    private final String xmlPath = "http://www.w3schools.com/xml/cd_catalog.xml";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parse_xml);
        try {
            xmlPullParserFactory = XmlPullParserFactory.newInstance();
            xmlPullParserFactory.setNamespaceAware(false);
            parser = xmlPullParserFactory.newPullParser();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
        displayXmlContent = (TextView)findViewById(R.id.display_xml);
        Button loadXmlButton = (Button)findViewById(R.id.load_xml_file);
        loadXmlButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BackgroundAsyncTask backgroundAsyncTask = new BackgroundAsyncTask();
                backgroundAsyncTask.execute(xmlPath);
            }
        });
    }
    private class BackgroundAsyncTask extends AsyncTask<String, Void, String>{
        @Override
        protected String doInBackground(String ...params) {
            URL url = null;
            String returnedResult = "";
            try {
                url = new URL(params[0]);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            HttpURLConnection conn = null;
            try {
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(20000);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                conn.connect();
                InputStream is = conn.getInputStream();
                parser.setInput(is, null);
                returnedResult = getLoadedXmlValues(parser);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            }
            return returnedResult;
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(!s.equals("")){
                displayXmlContent.setText(s);
            }
        }
        private String getLoadedXmlValues(XmlPullParser parser) throws XmlPullParserException, IOException {
            int eventType = parser.getEventType();
            String name = null;
            Entity mEntity = new Entity();
            while (eventType != XmlPullParser.END_DOCUMENT){
                if(eventType == XmlPullParser.START_TAG){
                    name = parser.getName();
                    if(name.equals("TITLE")){
                        mEntity.title = parser.nextText();
                    }
                    else if(name.equals("ARTIST")){
                        mEntity.artist = parser.nextText();
                    }
                    else if(name.equals("COUNTRY")){
                        mEntity.country = parser.nextText();
                    }
                    else if(name.equals("COMPANY")){
                        mEntity.company = parser.nextText();
                    }
                    else if(name.equals("PRICE")){
                        mEntity.price = parser.nextText();
                    }
                    else if(name.equals("YEAR")){
                        mEntity.year = parser.nextText();
                    }
                }
                eventType = parser.next();
            }
            return mEntity.title + ", " + mEntity.artist + ", " + mEntity.country + ", " + mEntity.company + ", " + mEntity.price + ", " + mEntity.year;
        }
        public class Entity{
            public String title;
            public String artist;
            public String country;
            public String company;
            public String price;
            public String year;
        }
    }
}

You have seen how you can use any of these libraries and default download manager in android.

This brings us to the end of this tutorial, If you find anything confusing kindly contact me with your questions or use the comment box below.

Now, when you run your application you will see the interface that looks similar to the sample that was shown earlier on.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email address so that you will be among the first to receive my new post once it is published.

Please if you love this tutorial, kindly download my new android app – Daily Pocket Calculator – in Google Play Store and let me know what you think about it.

8 Comments

    • Inducesmile

Add a Comment