Skip navigation

I’ve been working through the sample applications in Hello, Android, 3rd edition by Ed Burnette. One of the example programs utilizes the Google Translate API, which was abruptly changed to paying developers only last May. Fortunately, Google is not quite yet completely indispensable to the Net, and so I substituted the web service calls to the Microsoft Translator API. Much to my chagrin, however, Translation returns XML string objects, instead of JSON (as Google Translate does)-

<string xmlns="">feliz</string>

Mobile Orchard mentions three different XML parsers for Android – the SAX (Simple API for XML), pull, and DOM parsers. I opted to use the second, the XMLPullParser for my app due to its relatively lightweight nature.

// parse to get translated text
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader (payload));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
  if (eventType == XmlPullParser.TEXT) {
    result = xpp.getText();
  eventType =;

After the pull parser is created from the factory, it iterates through the XML in the while loop. In my case, I only wanted the element contents between the <string> tags, so I set it to search for TEXT. In contrast, the DOM parser would have to go through the entire DOM, and the SAX parser requires overriding several methods, both overkill for the one-element response I’m expecting.

For future projects involving more extensive XML parsing, I would have to consider these alternatives more. Like the pull parser, the SAX parser is event-driven, and so does not store anything in memory. While this is more efficient, it prevents random access to any part of the XML file if necessary. The DOM parser, on the other hand, does store the entire document in memory and that enables random access of XML nodes. SAX and pull parsers are different in that the former requires setting up callbacks; in Android, you would override four methods that are each respectively fired when the parser either arrives at the beginning of the XML document, at the start of an XML node, at the end of an XML node, or when it reads the XML node values. A comparison of the three XML parsers showed that SAX has the best performance, but pull parsers aren’t too far behind. Ultimately, what’s most important is for what purpose you need an XML parser for. Personally, I’d prefer to work with JSON.


Leave a Reply

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

You are commenting using your 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

%d bloggers like this: