Amazon Gift Cards

Sunday, May 31, 2009

How to use XmlPullParser in Android

A post from 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();
  XmlPullParser parser = factory.newPullParser(); 
  parser.setInput(new InputStreamReader(getUrlData(url)));  
  int eventType = parser.getEventType();
    eventType = parser.getEventType();
    if(eventType == XmlPullParser.TEXT){
  } 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();

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 on the current tag.

References (See this to understand the eventType stuff)

Update History
   Jan 17, 2012 - Visual Update


Unknown said...

Thanks! this was useful

MegadanX4 said...

Thank you, this helped me a lot! :D