Android Tutorial – How to Use XML Parser Android with Simple Example for Beginner

Seegatesite – I’ll share how to create xml parser android to retrieve xml data from a website. Continuing my articles about programming android, android xml parser used in order to communicate with a webservice that displays data in xml format. Android developer on the site, the use of XML parser is very easy to understand, I will discuss how to use xml parser in android with more simple examples to make it more easily understood by beginners.

There are various XML parsers we can use on the Android platform. For XML, Android recommends the use of the XMLPullParser.

We recommend XmlPullParser , which is an efficient and maintainable way to parse XML on Android.

As a beginner, I use the library XMLPullParser for ease of use.

Tutorial how to use of XML Parser android with XMLPullParser step by step

1. Make a simple xml file on your PHP server as rss.xml and place it in the folder “android” as shown below (If using xampp, the htdocs folder -> Android -> rss.xml)

How To Create Xml Parser Android With Xmlpullparser Step By Step

Then copy these script on your rss.xml

<?xml version="1.0" encoding="UTF-8"?>
<feed>

<article>
	<title>Android Tutorial – Switch Between Activity With Android Button Click For Beginner</title>
	<link url="http://seegatesite.com/android-tutorial-switch-between-activity-with-android-button-click-for-beginner/" />
</article>


<article>
	<title>[ Problems Solved ] – Fixed ADB Not Responding On Android Studio Or Eclipse</title>
	<link url="http://seegatesite.com/problems-solved-fixed-adb-not-responding-on-android-studio-or-eclipse/" />
</article>

</feed>

Please check your browser does xml has been loaded properly.

How To Create Xml Parser Android Android Tutorial

The next step we will begin to make the main parts android app

1. Create an android project in advance, if you don’t know how to create android project on android studio, please read the introduction android for beginner. In this example I gave the name BelajarXmlParser

2. Create a java class as RssXmlParser.java then copy the following script

package com.example.sigit.belajarxmlparser; // change with your package name

import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class RssXmlParser {
    private static final String ns = null;
    public List<Entry> parse(InputStream in) throws XmlPullParserException, IOException {
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(in, null);
            parser.nextTag();
            return readFeed(parser);
        } finally {
            in.close();
        }
    }
    private List<Entry> readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
        List<Entry> entries = new ArrayList<Entry>();
        parser.require(XmlPullParser.START_TAG, ns, "feed");
        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            String name = parser.getName();
            if (name.equals("article")) {
                entries.add(readEntry(parser));
            } else {
                skip(parser);
            }
        }
        return entries;
    }
    public static class Entry {
        public final String url;
        public final String title;

        private Entry(String url,String title) {
            this.url = url;
            this.title=title;
        }
    }
    private Entry readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
        parser.require(XmlPullParser.START_TAG, ns, "article");
        String title = null;
        String link = null;
        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            String name = parser.getName();
            if (name.equals("title")) {
                title = readTitle(parser);
            } else if (name.equals("link")) {
                link = readLink(parser);
            } else {
                skip(parser);
            }
        }
        return new Entry(link,title);
    }
    private String readTitle(XmlPullParser parser) throws IOException, XmlPullParserException {
        parser.require(XmlPullParser.START_TAG, ns, "title");
        String title = readText(parser);
        parser.require(XmlPullParser.END_TAG, ns, "title");
        return title;
    }
    private String readLink(XmlPullParser parser) throws IOException, XmlPullParserException {
        String link = "";
        parser.require(XmlPullParser.START_TAG, ns, "link");
        String tag = parser.getName();
        if (tag.equals("link")) {
                link = parser.getAttributeValue(null, "url");
                parser.nextTag();
        }
        parser.require(XmlPullParser.END_TAG, ns, "link");
        return link;
    }
    private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
        String result = "";
        if (parser.next() == XmlPullParser.TEXT) {
            result = parser.getText();
            parser.nextTag();
        }
        return result;
    }

    private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            throw new IllegalStateException();
        }
        int depth = 1;
        while (depth != 0) {
            switch (parser.next()) {
                case XmlPullParser.END_TAG:
                    depth--;
                    break;
                case XmlPullParser.START_TAG:
                    depth++;
                    break;
            }
        }
    }
}

A brief description :

Which need to be understood to xml parser as a beginner android programmer is two following sript

I. Looping the parent TAG

While Xml Parser To Get Xml Text How To Use Xml Parser Android For Beginner

If the parent’s TAG has child tags, we should use a while loop to retrieve the text on the tag inside.

II. Taking Text in a TAG

Get Text From Tag Xml How To Use Xml Parser Android

To get the text in the tag starts with parser.require (XmlPullParser.START_TAG, ns, “title”); and ends with parser.require (XmlPullParser.END_TAG, ns, “title”); .

Please read more detail on developer.android.com

– To get the text value required the following method

Gettext Xml Parser How To Use Xml Parser Android For Begginer

3. Open your activity_main.xml and copy the following script

<?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.example.sigit.belajarxmlparser.MainActivity"> 
    <WebView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" />
</RelativeLayout>

Remember to replace com.example.sigit.belajarxmlparser with the name of your package. We create WebView element to display results from xml parser.

4. Add the following script on string.xml the folder res -> values -> strings.xml

Add New Value On Strings Xml How To Use Xml Parser Android Developer

    <string name="connection_error">Unable to load content. Check your network connection.</string>
    <string name="xml_error">Error parsing XML.</string>

5. Add scripts on MainActivity.java (main script)

package com.example.sigit.belajarxmlparser; // change with your package name

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.AsyncTask;
import android.webkit.WebView;
import com.example.sigit.belajarxmlparser.RssXmlParser.Entry;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String URL =
            "http://192.168.1.20/android/rss.xml";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onStart() {
        super.onStart();
        loadPage();
    }
    private void loadPage() {
        new DownloadXmlTask().execute(URL);
    }

    private class DownloadXmlTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {
            try {
                return loadXmlFromNetwork(urls[0]);
            } catch (IOException e) {
                return getResources().getString(R.string.connection_error);
            } catch (XmlPullParserException e) {
                return getResources().getString(R.string.xml_error);
            }
        }
        @Override
        protected void onPostExecute(String result) {
            setContentView(R.layout.activity_main);
            WebView myWebView = (WebView) findViewById(R.id.webview);
            myWebView.loadData(result, "text/html", null);
        }
    }


    private String loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
        InputStream stream = null;
        RssXmlParser feedXmlParser = new RssXmlParser();
        List<Entry> entries = null;
        String url = null;
        StringBuilder htmlString = new StringBuilder();
       try {
            stream = downloadUrl(urlString);
            entries = feedXmlParser.parse(stream);
        } finally {
            if (stream != null) {
                stream.close();
            }
        }

        for (Entry entry : entries) {
          htmlString.append("

<a href='"); htmlString.append(entry.url); htmlString.append("'>" + entry.title + "</a>

");

        }
        return htmlString.toString();
    }
    private InputStream downloadUrl(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.connect();
        InputStream stream = conn.getInputStream();
        return stream;
    }

}


Explanation :

I use AsyncTask class to execute xml parser script (RssXmlParser.java) that we created before. For a full explanation of AsyncTask class I will discuss in another opportunity.

Using Asynctask For Execute Xml Parser Script How To Use Xml Parser Android Step By Step

When AsyncTask in execution, it’s will run the two procedures doInBackground and onPostExecute

– doInBackground call the loadXmlFromNetwork’s method

Execute Xml Parser From Main Activity Android How To Use Xml Parser Android For Beginner
Taking xml via the address “http://192.168.1.20/android/rss.xml” with the DownloadUrl method , then parser the xml file with RssXmlParser class that we created before into array list (entries = feedXmlParser.parse (stream );)

To sort through the array list above using the following functions

for (Entry entry : entries) {
 htmlString.append("<a href='"); htmlString.append(entry.url); htmlString.append("'>" + entry.title + "</a>");
        }

– onPostExecute will display the xml parser results into a WebView’s layout that we created earlier on activity_main.xml

When the application is executed the results are as shown below

How To Use Xml Parser Android For Begginer Step By Step

Don’t forget to add the following script on AndroidManifest.xml

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

Download example how to use XMLFullParser  in the link below

Read another tutorial android here

Thus article about Android Tutorial – How to Use XML Parser Android with Simple Example for Beginner, hope useful 🙂

 

The following two tabs change content below.
This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

7 Comments

 Add your comment
  1. this goo.gl shortlink has been disabled. It was found to be violating our Terms of Service. Click here and here for more information about our terms and policies respectively.

    so? where can I download? Thx?!

  2. It doesn’t work: IOExeption, “Unable to load content. Check your network connection.”

  3. Hello Sigit,

    many thanks for this great tutorial. You helped me a lot to undestand how to parse xml. 🙂

    There are still some points unclear. May I ask you some questions about it please? 🙂

    The script which you parse has html tags like title or url. Is it also possible to parse a xml-script which looks like this:

    1
    Harry Potter
    J. K. Rowling
    Fantasy
    5.95

    2
    The Hunger Games
    Suzanne Collins
    Fantasy
    8.99

    3
    Asterix and Obelix
    René Goscinny
    Fantasy
    1.99

    Do I have to parse this to Html, too?

    Thank you in Advance.

    Maria – a complete beginner 😉

  4. Ok, last try. 🙂 I left out the following sign:
    “data>
    “book>
    “id>1
    “name>Harry Potter
    “author>J. K. Rowling
    “genre>Fantasy
    “price>5.95
    “/book>

  5. 🙂 Now it worked. More or less. 🙂

    I am sorry for making such strange comments.

    Have a nice day and thank you. 🙂

Leave a Comment

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

%d bloggers like this: