Archive
Posts Tagged ‘xml’
Parsing XML with XmlPullParser
January 17, 2012
6 comments
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;
}
}
Categories: Researches
Android, androidapp, AndroidApps, Java, Tutorial, xml, xmlpullparser



