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.

No comments:

Post a Comment