Home > Researches > Parsing XML with XmlPullParser

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;
  }
}
About these ads
  1. April 29, 2012 at 9:01 pm

    i’m trying this code into my android app but it doesn’t work… is special lib required ? thanx

  2. Jundi
    July 17, 2012 at 3:00 pm

    not working…

  3. Jundi
    July 17, 2012 at 6:12 pm

    After searching i made it work!

    Need to put this code into a AsyncTask

  4. vishal
    September 4, 2012 at 10:00 am

    Thanx for d simplest code.. good job!! m new on android.helped alot

  1. March 26, 2012 at 9:32 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 507 other followers

%d bloggers like this: