Parsing XML with XmlPullParser

XmlPullParser is an interface that provides parsing functionality. The below code is an example of XmlPullParser usage.

We will parse the Youtube feed that contains the most highly rated YouTube video, looking for “<title>” tag and extracting the text inside.

URL Feed: https://gdata.youtube.com/feeds/api/standardfeeds/top_rated


//We will put the data into a StringBuilder
StringBuilder builder=new StringBuilder();

URL url = new URL("https://gdata.youtube.com/feeds/api/standardfeeds/top_rated");

XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp=factory.newPullParser();

xpp.setInput(getInputStream(url), "UTF_8");

int eventType=xpp.getEventType();
while(eventType!=XmlPullParser.END_DOCUMENT){
  // Looking for a start tag
  if(eventType==XmlPullParser.START_TAG){
    //We look for "title" tag in XML response
    if(xpp.getName().equalsIgnoreCase("title")){
      //Once we found the "title" tag, add the text it contains to our builder
      builder.append(xpp.nextText()+"\n");
    }
  }

  eventType=xpp.next();
}

And here’s the implementation of getInputStream() method:

public InputStream getInputStream(URL url) {
  try {
    return url.openConnection().getInputStream();
  } catch (IOException e) {
    return null;
  }
}

6 thoughts on “Parsing XML with XmlPullParser

Leave a comment