Parsing XML using jQuery

I was recently asked if there was a simple way to parse XML using jQuery. My answer was I would always prefer serializing my data to JSON and then read it using jQuery. However if you do not have that option available for some reason, here’s a simple example of reading an XML document using jQuery

Assuming you have made a $.ajax() call and have a string with XML data. Here’s how to read it

Parse XML jQuery

The example is very simple. We are using the jQuery.find to get the descendants of each element that matches the selector and then adding the values in a paragraph using append().

Note: In IE8, this example won’t work. However in a real app scenario, you would use an ajax call to read the XML. Just use content-type: text/xml in your XML and this will fetch you  an XML object which can be read in IE8.

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: