Saturday 28 September 2013

Android XML Parsing


I have a requirement to read the XML content in Android project.
So googling for long time and people are talking about the JAXB versionof android and XML to POJO utilities etc...but I found that Android itself has own API to read XML content, which is beautiful.

I came across this API which I will give you the example here .
It also has the better implementations of SAX parsers inside the android .

you can go through this :
http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html
which is from ANDROID SDK exmaples itself.

I don't know when will this be removed or updated from the site or for quick reference I am pasting here.

================

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

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

 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");
     }
 }
 
The above example will generate the following output:
 Start document
 Start tag foo
 Text Hello World!
 End tag foo
 End document