Tuesday, 29 October 2013

XML PullParser

 1.There are two key methods: next() and nextToken(). While next() provides access  to high level    
     parsing events, nextToken()  allows access to lower level tokens.

2.The current event state of the parser can be determined by calling the getEventType()   
    method.Initially, the parser is in the  START_DOCUMENT state 

3.The method next() advances the parser to the next event.

The following event types are seen by next()
START_TAG: An XML start tag was read.
TEXT: Text content was read; the text content can be retrieved using the getText() method.
END_TAG: An end tag was read

END_DOCUMENT: No more events are available


Example:
public class SimpleXmlPullApp
 {

     public static void main (String args[])
         throws XmlPullParserException, IOException
     {
         XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
         factory.setNamespaceAware(true);
         XmlPullParser xpp = factory.newPullParser();

         xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) );
         int eventType = xpp.getEventType();
         while (eventType != XmlPullParser.END_DOCUMENT) {
          if(eventType == XmlPullParser.START_DOCUMENT) {
              System.out.println("Start document");
          } else if(eventType == XmlPullParser.START_TAG) {
              System.out.println("Start tag "+xpp.getName());
          } else if(eventType == XmlPullParser.END_TAG) {
              System.out.println("End tag "+xpp.getName());
          } else if(eventType == XmlPullParser.TEXT) {
              System.out.println("Text "+xpp.getText());
          }
          eventType = xpp.next();
         }
         System.out.println("End document");
     }
 }



Example Application:

activity_main.xml:
<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=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>


MainActivity.java:
package com.ram.xmlpullparser;

import java.io.IOException;
import java.net.URL;

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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;

@SuppressLint("NewApi")
public class MainActivity extends Activity {
    TextView text;

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

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);

        text = (TextView) findViewById(R.id.textView1);

        try {
            parse();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    void parse() throws IOException, XmlPullParserException {

        URL url = new URL("http://www.w3schools.com/xml/note.xml");

        // Create a new instance of a PullParserFactory that can be used to
        // create XML pull parsers

        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();

        // Specifies that the parser produced by this factory will provide
        // support for XML namespaces. By default the value of this is set to
        // false.

        factory.setNamespaceAware(true);

        // Creates a new instance of a XML Pull Parser using the currently
        // configured factory features

        XmlPullParser xpp = factory.newPullParser();

        // Sets the input stream the parser is going to process. This call
        // resets the parser state and sets the event type to the initial value
        // START_DOCUMENT.

        xpp.setInput(url.openStream(), null);

        // Returns the type of the current event (START_TAG, END_TAG, TEXT,
        // etc.)

        int eventType = xpp.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {

               //  text.append(xpp.getName());
            } else if (eventType == XmlPullParser.TEXT) {

                text.append(xpp.getText());
            } else if (eventType == XmlPullParser.END_TAG) {

                // text.append(xpp.getName());
            }
            eventType = xpp.next();
        }
    }
}


AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ram.xmlpullparser"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.xmlpullparser.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>


ScreenShot: