Parsing XML Using the XML Pull Parser in Android

The XML Pull Parser API is available from the following libraries:

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

It enables you to parse an XML document in a single pass. Unlike the DOM parser, the Pull Parser presents the elements of your document in a sequential series of events and tags

Your location within the document is represented by the current event. You can determine the current event by calling getEventType. Each document begins at the START_DOCUMENT event and ends at END_DOCUMENT.

To proceed through the tags, simply call next, which causes you to progress through a series of matched (and often nested) START_TAG and END_TAG events. You can extract the name of each tag by calling getName and extract the text between each set of tags using getNextText.

Parsing XML using the XML Pull Parser

private void processStream(InputStream inputStream) {
 // Create a new XML Pull Parser.
 XmlPullParserFactory factory;
 try {
 factory = XmlPullParserFactory.newInstance();
 factory.setNamespaceAware(true);
 XmlPullParser xpp = factory.newPullParser();
 // Assign a new input stream.
 xpp.setInput(inputStream, null);
 int eventType = xpp.getEventType();
 // Continue until the end of the document is reached.
 while (eventType != XmlPullParser.END_DOCUMENT) {
 // Check for a start tag of the results tag.
 if (eventType == XmlPullParser.START_TAG && 
 xpp.getName().equals(“result”)) {
 eventType = xpp.next();
 String name = “”;
 // Process each result within the result tag.
 while (!(eventType == XmlPullParser.END_TAG && 
 xpp.getName().equals(“result”))) {
 // Check for the name tag within the results tag.
 if (eventType == XmlPullParser.START_TAG && 
 xpp.getName().equals(“name”))
 // Extract the POI name.
 name = xpp.nextText();
// Move on to the next tag.
 eventType = xpp.next();
 }
 // Do something with each POI name.
 }
 // Move on to the next result tag.
 eventType = xpp.next();
 }
 } catch (XmlPullParserException e) {
 Log.d(“PULLPARSER”, “XML Pull Parser Exception”, e);
 } catch (IOException e) {
 Log.d(“PULLPARSER”, “IO Exception”, e);
 }
}

Leave a Comment