Android Parse Xml Use XmlPullParser Example

This example show you how to use XmlPullParserFactory and XmlPullParser to parse xml file and show the parsed out data in text view.

android parse xml use xmlpullparser example

To run this example, you need to use OkHttp3 library in your android project. Please read Android OkHttp3 Http Get Post Request Example to learn how to do it.

The xml file url in this example is http://dev2qa.com/demo/xml/employee.xml. When click the button, it will read that xml file content, and parse the data in it and display in bottom textview.

1. Main Activity.

The parseXmlUsePullParser(String xmlString) method in below code implement parse xml and return a formatted string action.

XmlPullParserActivity.java

package com.dev2qa.example.xml;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.TextView;

import com.dev2qa.example.R;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.StringReader;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class XmlPullParserActivity extends AppCompatActivity {

    // Tag name for log data.
    private static final String TAG_XML_PULL_PARSER = "XML_PULL_PARSER";

    // Message command for activity handler to show xml parse result.
    private static final int MESSAGE_SHOW_XML_PARSE_RESULT = 1;

    // Message data bundle key to save xml parsed result.
    private static final String KEY_XML_PARSE_RESULT = "KEY_XML_PARSE_RESULT";

    // Parse xml use XmlPullParser button.
    private Button parseXmlUsePullButton = null;

    // Display xml parse result text view.
    private TextView showXmlParseResultTextView = null;

    // This handler is waiting for child thread message to display xml parse result in text view.
    private Handler showParseResultHandler = null;

    // OkHttpClient to read xml file from url.
    private OkHttpClient okHttpClient = null;

    // This is xml file url.
    private String xmlFileUrl = "http://www.dev2qa.com/demo/xml/employee.xml";

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

        setTitle("dev2qa.com - Android XmlPullParser Example.");

        // Init all ui controls first.
        initControls();

        // Click this button to parse xml url use XmlPullParser.
        parseXmlUsePullButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(URLUtil.isHttpUrl(xmlFileUrl) || URLUtil.isHttpsUrl(xmlFileUrl)) {
                    // Create a OkHttpClient request builder.
                    Request.Builder builder = new Request.Builder();

                    // Set xml file url.
                    builder  = builder.url(xmlFileUrl);

                    // Build http request.
                    Request request = builder.build();

                    // Create a OkHttp3 Call object.
                    Call call = okHttpClient.newCall(request);

                    // Execute the get xml file request asynchronously in an automate child thread.
                    call.enqueue(new Callback() {

                        // If http get request fail.
                        @Override
                        public void onFailure(Call call, IOException e) {
                            sendXmlParseResultToActivityHandler(e.getMessage());
                        }

                        // If http get request success.
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            // If server response success.
                            if(response.isSuccessful())
                            {
                                // Get response return xml string.
                                String resultXml = response.body().string();

                                // Parse the xml string.
                                String xmlParseResult = parseXmlUsePullParser(resultXml);

                                // Send message to activity main thread Handler to show the xml parsed result.
                                sendXmlParseResultToActivityHandler(xmlParseResult);
                            }
                        }
                    });
                }
            }
        });

    }

    /* Send message to activity main thread Handler to display xml parse result. */
    private void sendXmlParseResultToActivityHandler(String xmlParseResult)
    {
        // Create message object.
        Message msg = new Message();
        msg.what = MESSAGE_SHOW_XML_PARSE_RESULT;

        // Add error message in message object data.
        Bundle bundle = new Bundle();
        bundle.putString(KEY_XML_PARSE_RESULT, xmlParseResult);
        msg.setData(bundle);

        // Send message to activity ui update Handler.
        showParseResultHandler.sendMessage(msg);
    }



    /* Parse xml string use XmlPullParser.Return parsed string. */
    private String parseXmlUsePullParser(String xmlString)
    {
        StringBuffer retBuf = new StringBuffer();

        try {
            // Create xml pull parser factory.
            XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();

            // Create XmlPullParser.
            XmlPullParser xmlPullParser = parserFactory.newPullParser();

            // Create a new StringReader.
            StringReader xmlStringReader = new StringReader(xmlString);

            // Set the string reader as XmlPullParser input.
            xmlPullParser.setInput(xmlStringReader);

            // Get event type during xml parse.
            int eventType = xmlPullParser.getEventType();

            while(eventType != XmlPullParser.END_DOCUMENT) {
                // Get xml element node name.
                String nodeName = xmlPullParser.getName();

                if (!TextUtils.isEmpty(nodeName)) {
                    if (eventType == XmlPullParser.START_TAG) {
                        Log.d(TAG_XML_PULL_PARSER, "Start element " + nodeName);

                        if ("user".equalsIgnoreCase(nodeName) || "email".equalsIgnoreCase(nodeName) || "title".equalsIgnoreCase(nodeName)) {
                            retBuf.append(nodeName);

                            // Get xml element text value.
                            String value = xmlPullParser.nextText();

                            Log.d(TAG_XML_PULL_PARSER, "element text : " + value);

                            retBuf.append(" = ");
                            retBuf.append(value);

                            retBuf.append("\r\n\r\n");
                        }
                    } else if (eventType == XmlPullParser.END_TAG) {
                        Log.d(TAG_XML_PULL_PARSER, "End element " + nodeName);
                        if("employee".equalsIgnoreCase(nodeName))
                        {
                            retBuf.append("************************\r\n\r\n");
                        }
                    }
                }

                eventType = xmlPullParser.next();
            }
        }catch(XmlPullParserException ex)
        {
            // Add error message.
            retBuf.append(ex.getMessage());
        }finally {
            return retBuf.toString();
        }
    }

    // Initialize ui controls.
    private void initControls()
    {
        if(parseXmlUsePullButton == null)
        {
            parseXmlUsePullButton = (Button)findViewById(R.id.xml_pull_parser_parse_button);
        }

        if(showXmlParseResultTextView == null)
        {
            showXmlParseResultTextView = (TextView)findViewById(R.id.xml_parse_result_text_view);
        }

        if(showParseResultHandler == null)
        {
            // This handler waiting for message from activity child thread.
            showParseResultHandler = new Handler()
            {
                @Override
                public void handleMessage(Message msg) {
                    // If the message want to display xml parse result.
                    if(msg.what == MESSAGE_SHOW_XML_PARSE_RESULT)
                    {
                        // Get message bundle data.
                        Bundle bundle = msg.getData();

                        // Get xml parse result.
                        String xmlParseResult = bundle.getString(KEY_XML_PARSE_RESULT);

                        // Show the result in text view.
                        showXmlParseResultTextView.setText(xmlParseResult);
                    }
                }
            };
        }

        if(okHttpClient == null)
        {
            okHttpClient = new OkHttpClient();
        }
    }
}

2. Layout Xml File.

activity_xml_pull_parser.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/xml_pull_parser_file_url_editor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="http://www.dev2qa.com/demo/xml/employee.xml"/>

    <Button
        android:id="@+id/xml_pull_parser_parse_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Parse Xml Use Pull Parser"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/xml_parse_result_text_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

</LinearLayout>

3. Android Manifest Xml File.

Because this example need to access internet, so it need below permission.

READ :   How To Mirror Android Screen On Mac, PC Via USB

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dev2qa.example">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
        <activity android:name=".xml.XmlPullParserActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Reference

  1. http://www.xmlpull.org/
(Visited 593 times, 8 visits today)

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.