Friday, September 16, 2011

Simpler and Easier XML Parsing in Android

 

xml_5+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.

XmlDom

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.

Simple

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 = "https://picasaweb.google.com/data/feed/base/featured?max-results=8";        
    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){
        titles.add(entry.text("title"));
        imageUrl = entry.tag("content", "type", "image/jpeg").attr("src");
    }
        
    aq.id(R.id.image).image(imageUrl);
    
}}
 
 
Constructors
 
 
XmlDom(String str)
 
XmlDom(byte[] data)
 
XmlDom(InputStream is)
 
XmlDom(Element element)
Methods

[javadoc]

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");
 
text()
 
//extract the text value of the title tag
String text = title.text();
 
attr()
 
//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

[source]

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.

AQuery

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

No comments:

Post a Comment