Posted by – February 22, 2012
I recently worked on a small Android App using PhoneGap & jQuery. The app did a very small task fetch the XML feed from my blog and display it. Simple. This meant parsing XML using jQuery. Most of the examples on web used this particular example in one form or another. Not all XML document are like record sets. For example a blog feed will have following structure
<?xml version="1.0" encoding="UTF-8"?>
<title>LAMP Web Development Blog</title>
<item id="item1" somerandomattribute="attribute value">
<title>My first Android App or how to develop an Android App using PhoneGap and jQuery?</title>
<title>How not to do a CI controller? – Tips to develop CodeIgniter Controllers</title>
The interesting part in this XML is that tags or nodes with similar names exist through out the document at different depth. This XML has attributes attached to its nodes. This is how a typical XML may look like. How do you actually parse this using jQuery? jQuery has find(). From the documentation
Given a jQuery object that represents a set of DOM elements, the .find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements.
We can convert this XML into a jQuery object and then use find() to actually parse it. Here is a code snippet
var xml = '<?xml version="1.0" encoding="UTF-8"?> <channel> <title ...>', //your XML string goes here
feedtitle = $(xml).find('channel title:first'), //find first tag or node in XML that is named title
feedlink = $(xml).find('channel link:first'); //find first tag or node in XML that is named link
$(xml).find( "item" ).each(
var item = $(this),
title = item.find('title').text(),
link = item.find('link').text(),
itemid = item.attr('id');//get an attribute
//you can log all attributes
You can see a complete example on this git page and check out the code as well. Things to note here:
- You can use filters with selectors.
- You can find() a node/element and then you have all the attributes available it in “attributes” list.
- You can traverse the list or use .attr() to actually find and use an attribute.