Friday, February 1, 2013

Android XMLPull Parser example


One big problem the SAX model has is that it is push based: Once the parsing is started, parsing events are pushed in continuously. The parser runs through the entire XML document in one pass. Developers have no control over the flow of the parsing process. For example, let's suppose that you are looking for a specific piece of information located in the middle of an XML document. Under the SAX model, you cannot stop parsing after you retrieve the data. The parse keeps going until it finishes the entire document. This is ineffective, especially for mobile clients.

The heart of the XmlPull API is the XmlPullParser interface. XmlPull providers supply their own XmlPullParser implementation through the XmlPullParserFactory factory class. XmlPullParser defines a number of event types (e.g., the START_TAG event) and data access methods (e.g., the getAttributeValue() method). Core methods to control the parsing flow are next() and nextToken().
  • The next() method advances the parser to the next event. Event types seen by the next() method are START_TAG, TEXT, END_TAG, and END_DOCUMENT.
  • The nextToken() method gives developers a finer control. It sees all the events the next() method sees. In addition, it sees and reports the following events: COMMENT, CDSECT, DOCDECL, ENTITY_REF, PROCESSING_INSTRUCTION, and IGNORABLE_WHITESPACE.

    The use of an XmlPull parser is illustrated here :

    make a project and have a mainactivity with the following code

    package com.jitesh.simplexmlpullapp;

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

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

    import android.os.Bundle;
    import android.app.Activity;
    import android.content.res.AssetManager;
    import android.view.Menu;
    import android.widget.TextView;

    public class MainActivity extends Activity {
    private TextView xmlOutput;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    xmlOutput = (TextView) findViewById(R.id.xmlOutput);
    try {
    try {
    parseXML();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    } catch (XmlPullParserException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    private void parseXML() throws XmlPullParserException, IOException {
    String parsedData = "";
    String textforinput = "<foo>Hello World!</foo>";

    // TODO Auto-generated method stub
    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    factory.setNamespaceAware(true);
    XmlPullParser xpp = factory.newPullParser();
    // new InputSource(getAssets().open("data.txt"))
    // To load text file
    AssetManager assetManager = getAssets();
    InputStream input;
    try {
    input = assetManager.open("data.txt");

    int size = input.available();
    byte[] buffer = new byte[size];
    input.read(buffer);
    input.close();

    // byte buffer into a string
    textforinput = new String(buffer);

    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    xpp.setInput(new StringReader(textforinput));
    int eventType = xpp.getEventType();
    parsedData = parsedData + "----->\n";
    while (eventType != XmlPullParser.END_DOCUMENT) {
    if (eventType == XmlPullParser.START_DOCUMENT) {
    System.out.println("Start document");

    } else if (eventType == XmlPullParser.END_DOCUMENT) {
    System.out.println("End document");
    } else if (eventType == XmlPullParser.START_TAG) {
    System.out.println("Start tag " + xpp.getName());
    parsedData = parsedData + "Start tag " + xpp.getName() + "\n";
    } else if (eventType == XmlPullParser.END_TAG) {
    System.out.println("End tag " + xpp.getName());
    parsedData = parsedData + "End tag " + xpp.getName() + "\n";
    } else if (eventType == XmlPullParser.TEXT) {
    System.out.println("Text " + xpp.getText());
    parsedData = parsedData + "Text " + xpp.getText() + "\n";
    }
    parsedData = parsedData + "----->\n";
    xmlOutput.setText(parsedData);

    eventType = xpp.next();
    }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }
    }


    the main.xml is having the following layout

    <ScrollView 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

    <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" >

        <TextView
            android:id="@+id/xmlOutput"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </RelativeLayout>
    </ScrollView> 

    the data.xml is present at asset/data.txt

    <Items>
        <ItemData>
            <ItemNumber>ABC</ItemNumber>
            <Description>ABC Item Description</Description>
            <Price>9.95</Price>
            <Weight>10.00</Weight>
        </ItemData>
        <ItemData>
            <ItemNumber>XYZ</ItemNumber>
            <Description>XYZ Item Description</Description>
            <Price>19.95</Price>
            <Weight>22.22</Weight>
        </ItemData>
    </Items>

    you can see the output as given below screen shot


    the source code can be downloaded from Simple Pull Parser





3 comments:

  1. You need to take an effort to contact them. You are the one who need them so you initiate the communication.

    ReplyDelete
  2. a well designed and developed ecommerce website always can increase your bussiness quality in the world.web insect developed the all kind of ecommerce website with the best design.seo services,android mobile applications are also provided by web insect

    ReplyDelete
  3. Bookmarked.
    very helpful.
    Thank you soo much..

    ReplyDelete