jQuery Makes Parsing XML Easy

May 05, 2007

I am building a Google Maps project and jQuery is making my life so much easier when parsing XML.

Regular JavaScript XML Parsing

var xmlDoc = request.responseXML;
try // Build Markers, if available
{
var markers = xmlDoc.getElementsByTagName("marker") ;
for ( var i = 0; i < markers.length ; i++ ) {
var point = {
markers[i].getAttribute("lat")),
markers[i].getAttribute("lng")
};
}
} catch(e) {}

jQuery XML Parsing

$(request.responseXML).find("marker").each(function() {
var marker = $(this);
var point = {
marker.attr("lat"),
marker.attr("lng")
};
});

The jQuery code is so much easier to read and understand. This is a basic example, but imagine when things get complex. After writing a few complex statements, you will realize the jQuery code will still be understandable, where as the JavaScript code will become hard to maintain. Thank you jQuery for making my job easier and more fun.

40 comments

#1. Forrest on November 07, 2007

Wow! quickly re-writes own code excitedly

#2. Ryan on November 07, 2007

One of the best things about ActionScript 3 is E4X syntax where this stuff is really easy. I’m looking forward to when JavaScript gets that upgrade and no JavaScript trickery is needed.

#3. Marc on November 07, 2007

Until then, jQuery is our upgrade to JavaScript. And it does a dang good job at it.

#4. yitz on December 25, 2007

thanks, this post was the decisive one in helping me to achieve successful xml parsing in jquery.. it was the perfect tutorial :)

#5. Mustafa on March 22, 2008

thank for good view about jquery, I will start it using

#6. ryan on October 09, 2008

thanks! that was super easy!! No ‘for’ loops or ‘getElementsByTagName

#7. Your name on October 09, 2008

Wont work on IE 7..

#8. Marc Grabanski on October 09, 2008

Depends on how you fetch the XML. I was using the Google XML loader and it worked fine in IE6+

#9. Martin Sarsini on October 11, 2008

Never thought could be so much simple!

#10. Fabio on February 21, 2009

It’s very useful !!!!

Fabio Rodrigues,
www.jmssolucoes.com.br

#11. Laga on February 27, 2009

Hi all,
Thank you for the example its very useful. And its definitely much easier than parsing with simple javascript.

though I have a question: Is there any tutorial that goes in more details??

Best regards,
Nassim

#12. Addy Osmani on February 28, 2009

Nice article! We recently had to parse RSS feeds from mySpace using nothing more than jQuery and we found a slightly quicker solution – jFeed. I would definitely recommend checking it out. As for our widget, you’re all free to grab the sources to see how we tackled the problem:
Download sources

#13. knowingPark on April 23, 2009

Thanks, saved my bacon. I promoted you on the googlator :)

#14. Matt on May 24, 2009

Definitely! using it now for a web based URL lookup tool, loads of xml responses – this speeded up development time and saved myself from any brain damage! :)

#15. Rodrigo on May 24, 2009

How do I get this working on IE7, what is the Google XML loader, I couldnt find anything about it on the web… I using my app’s generated raw XML and it doesnt work on IE =(

#16. Phil on June 17, 2009

Nice, but you’re essentially replacing 12 lines of JavaScript with a whole library of it instead. That said, 99.999% of all my projects use jQuery anyway! :)

#17. Mark on August 11, 2009

Thanks for the tip on this, I was writing out getElementByTagName and getAttribute and didn’t even think to just parse XML with JQuery.
I’m trying to figure out how to get to the Nth page in my XML this way but doesn’t seem like you can do $(xmlDoc).find(‘page’)8.attr(‘label’); I’ll keep googlin….

#18. Mark on August 11, 2009

ok $(xmldoc).find(‘page’).eq(8).attr(‘label’);

#19. Mark Howard on August 27, 2009

Like someone else said above… This post got me going and I couldn’t help myself but spend a late, late night rewriting my XML parsing functions to use jQuery. Now, I am very close to full cross-browser support.

I wish I would have started using jQuery years ago.

Thanks for the simple write-up showcasing jQuery’s awesomeness!

#20. slothbear on September 02, 2009

Thanks for this post — it helped me along in the jQuery world.

#21. Atea Webdevelopment on September 04, 2009

Thanks! Good examples that helped me!

#22. blogging developer on November 16, 2009

Great post. Thanks.

Here is a jQuery Plugin for easy XML parsing: http://www.bloggingdeveloper.com/post/Parse-XML-with-Javascript-jParse-jQuery-Plugin-for-Parsing-XML.aspx

#23. nongeek on December 07, 2009

Very useful, thanks.

I needed to parse some xml files and I found that the solution is right in my browser. jQuery makes it really easy. I prefer to use the ajax() method to retrieve the xml file, though.

#24. José Carlos on December 08, 2009

Nice post! I’m looking for something like this for hours !!

Congratulations !

#25. Danis on May 07, 2010

Hi,

Can we use jquery to get wordpress blog feed for a normal hand coded web site?
If yes what will be the modified code based on the example you have placed here?

Regards,
Danis

#26. Marc Grabanski on May 07, 2010

you can use YQL to get a feed. You can’t fetch remote XML requests natively with JavaScript.

#27. vuvuzela on July 26, 2010

expression was very nice thank you :)

#28. Niloc on August 16, 2010
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject(Microsoft.XMLDOM);
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, text/xml);
} else
return "";
}

and on success you parse to xml first:

success: function(data) {
var xml = parseXml(data);
$(xml).find("result").each(function() {

Use the above function parseXml() only when you don’t set the datatype of the $ajax request

#29. James on October 07, 2010

Hello,
I’m trying to do the same thing: a google map project loading marker from my database (helped by the tutorial of Google Documentation).
I didn’t understand why my variable data.responseXML is always “undefined”, have you any ideas ? (if I print data, i see my xml data :s)

var url = "load?id=" + id;
$.ajax({
type: GET,
url: url,
async: true,
success: function (data) {loadData(data);},
error: function(data) {alert("Error");}
});

function loadData(data) {
alert(data.responseXML); // (: undefined)
$(data.responseXML).find("marker").each(function() {
var marker = $(this);
var point = new google.maps.LatLng(marker.attr("lat"), marker.attr("lng"));
var new_marker = new google.maps.Marker({map: map, position: point});
});
}

Thanks :)

#30. MSX on October 12, 2010

Hello,

Thanks for this tutorial :)

I’m wondering how to write into an xml fil either with JS or jQuery ?

Thanks

#31. Renjith Maxy on October 21, 2010

Thanks dude i was searching for the same

#32. chris on October 22, 2010

thx and yeah, i also would like to know how you can write into an xml file with jQuery!

#33. Dan on November 09, 2010

For #29,
function loadData(data) {
alert(data); // (: undefined)
$(data).find(“marker”).each(function() {
var marker = $(this);
var point = new google.maps.LatLng(marker.attr(“lat”), marker.attr(“lng”));
var new_marker = new google.maps.Marker({map: map, position: point});
});
}

#34. Alex on December 18, 2010

Yeh, jQuery has been a time saver for me in so many tasks. Even when I need to parse XML, and apply the results to C# code, I would parse it in jQUery and then pass the data in C# program. :)

#35. Raju Jadhav on January 04, 2011
var count1=0; 
$.ajax({
type: "GET",
url: "jquery_xml.xml",
dataType: "xml",
success: function(xml) {
$(xml).find("Tutorial").each(function() {
//var marker = $(this);
count1 = count1+1;
});
}
});
alert(count1);
#36. Rahul Anand on January 06, 2011

Very Useful Article. Really Thanks to Jquery for making such a great library. I am really a big fan of Jquery and use it rather then other libraries.

#37. David D on January 16, 2011

It is a very good tutorial.

I am learning JQuery now, it helps me.

#38. rajesh on February 27, 2011

Simple example to read xml using jquery Here

#39. Yomodo on March 04, 2011

It’s still a pitty .responseXML cannot be used (anymore?)
When applying a .xsl which is also an xml, I have to convert it first
like: obj.loadXML(res.responseText) in order to use .transformNode()

#40. DIJO JOSEPH on November 08, 2011

function parseXml(str) {

if (window.ActiveXObject) {
var doc = new ActiveXObject(‘Microsoft.XMLDOM’);
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, ‘text/xml’);
} else
return "";

}

Leave a comment

Comment in textile images by gravatar