How to use XmlPullParser in Android

Public on May 31, 2009
A post from androidguys.com stated that using XmlPullParser instead of DOM might be better in power saving. As i non java guy, i first didn't know what this one is. So today i tried to examine how to use it. And here is what i come up with. Please comment if the stuff i did is wrong or could be further optimized.

Note: XmlUtils is by default not included in the SDK, you can grab the class here. If there is an error, just remove the error.

public static void getAllXML(String url) throws 
XmlPullParserException, IOException, URISyntaxException{
  XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
  factory.setNamespaceAware(true);
  XmlPullParser parser = factory.newPullParser();
  parser.setInput(new InputStreamReader(getUrlData(url)));
  XmlUtils.beginDocument(parser,"results");
  int eventType = parser.getEventType();
  do{
    XmlUtils.nextElement(parser);
    parser.next();
    eventType = parser.getEventType();
    if(eventType == XmlPullParser.TEXT){
      Log.d("test",parser.getText());
    }
  } while (eventType != XmlPullParser.END_DOCUMENT) ;
}
public InputStream getUrlData(String url)
throws URISyntaxException, ClientProtocolException, IOException {
  DefaultHttpClient client = new DefaultHttpClient();
  HttpGet method = new HttpGet(new URI(url));
  HttpResponse res = client.execute(method);
  return res.getEntity().getContent();
}



Explanation
The getAllXml function would call getUrlData that would return an InputStream and pass it to the XmlPullParser
XmlPullParser parser = factory.newPullParser();
parser.setInput(new InputStreamReader(getUrlData(url)));


Then we would loop through the whole xml. This part is a bit complicated to explain so i apologize in advance if you would understand the following sentences.
On the loop we first we have to find out, base on the parser, which eventType the current element is at. The common event type that you would use are START_DOCUMENT, END_DOCUMENT, START_TAG, END_TAG, TEXT. Since we use the XMLUtils, which have a function that would help us get the nextElement without worrying about the closetags, text or comments in between the current tag and the next tag. After we get the next element tag, we parse the next one and see if its a TEXT (This might have some errors on your xml), if its a TEXT then we do our magic here. If you have an attribute, you may use getAttribute before the parse.next() on the current tag.

References
TelephonyProvider.java
XmlSnapshot.java (See this to understand the eventType stuff)
WebClient.java

Update History
   Jan 17, 2012 - Visual Update




[Advertising]Faster Thinking - Speed up your brain


Faster Thinking Game



sentiment_satisfied Emoticon