jQuery Makes Parsing XML Easy
I am building a Google Maps project and jQuery is making my life so much easier when parsing XML.
Regular JavaScript XML Parsing
JavaScript:
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
JavaScript:
$(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.
Comments
Fabio Rodrigues,
www.jmssolucoes.com.br
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
Download sources
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....
I wish I would have started using jQuery years ago.
Thanks for the simple write-up showcasing jQuery's awesomeness!
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
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.
Congratulations !