Friday, September 16, 2011

Simpler and Easier XML Parsing in Android




XML Parsing Problem

Surprisingly, XML parsing is not as trivial as one might think in Android. XPath and XML Serialization is only supported in API level 8 or above, which drives many developers to uses third party libraries for XML related tasks.

AQuery XML Usage

One of the key feature of AQuery is asynchronous http fetch, which often is used to invoke REST type of services over the internet. These types of API/services, such as Facebook, Twitter, or Picasa (example provided in this post) usually serves results in XML and/or JSON formats for apps to consume.

For this purpose, AQuery wants to provide a simple, easy, and light-weight method to parse these XML responses. Such method must be independent on third party library and supports API level 4.


Here we introduce AQuery’s XmlDom. [source] [javadoc] [download]

XmlDom is a specialized class for simple and easy XML parsing, designed to be used in basic Android api 4+ runtime without any dependency, and integrated directly with AQuery’s ajax method.


Per AQuery’s philosophy, we want to make our tasks as simple as possible. Here’s an example that get an XML of featured images from Google’s Picasa service, parse the response, and display one of the featured image it in our app.

This is done with AQuery with just 10 lines of code.

public void xml_ajax(){        
    String url = "";        
    aq.ajax(url, XmlDom.class, this, "picasaCb");        
public void picasaCb(String url, XmlDom xml, AjaxStatus status){
    List<XmlDom> entries = xml.tags("entry");        
    List<String> titles = new ArrayList<String>();
    String imageUrl = null;
    for(XmlDom entry: entries){
        imageUrl = entry.tag("content", "type", "image/jpeg").attr("src");
XmlDom(String str)
XmlDom(byte[] data)
XmlDom(InputStream is)
XmlDom(Element element)


tag(), tags()

//return a list of "entry" nodes
List<XmlDom> entries = xml.tags("entry");  
child(), children()
//child is similar to tag, except it only return child nodes immediately under the parent
XmlDom title = entry.child("title");
//extract the text value of the title tag
String text = title.text();
//extract the src attribute of a content tag
String image = content.attr("src");
Serialization (beta)
//Convert a XmlDom object to a XML string
String rawXml = xml.toString();
Light Weight


There’s only 1 class with compressed size of ~3kb. Feel free to download the source and use it even without AQuery core lib.

API Demo

Checkout our API demo app to see this example in action.


For more Android development goodies, check out our AQuery home page.

1 comment:

  1. The Evolution of the 'Big Money' Casino - Filmfile Europe
    The 토토사이트 해킹 샤오미 Evolution of the 빌리버 'Big Money' Casino · 우회 주소 1. The Biggest 심바 사이트 Crypto-Casino · 2. Evolution Gaming 스포츠토토 판매점찾기 샤오미 · 3. NetEnt · 4.


AQuery Demo App