Copyright from: www.kumarchetan.com
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
LAMP Web Development Blog http://www.kumarchetan.com/blogMy first Android App or how to develop an Android App using PhoneGap and jQuery? http://www.kumarchetan.com/blog/2012/01/14/my-first-android-app-or-how-to-develop-an-android-app-using-phonegap-and-jquery/How not to do a CI controller? – Tips to develop CodeIgniter Controllers http://www.kumarchetan.com/blog/2011/12/11/how-not-to-do-a-ci-controller-tips-to-develop-codeigniter-controllers/
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 = '', //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( function(){ 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 //console.log(item[0].attributes); } );
You can see a complete example on this git page and check out the code as well. Things to note here:
No comments:
Post a Comment