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

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.

Comments

  1. Ryan says

    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.

  2. says

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

  3. Laga says

    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

  4. says

    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.

  5. says

    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! :)

  6. Rodrigo says

    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 =(

  7. says

    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! :)

  8. says

    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….

  9. says

    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!

  10. says

    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.

  11. says

    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

  12. Niloc says

    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

  13. James says

    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 :)

  14. MSX says

    Hello,

    Thanks for this tutorial :)

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

    Thanks

  15. Dan says

    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});
              });
            }

  16. says

    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. :)

  17. Raju Jadhav says

    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);

  18. says

    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.

  19. Yomodo says

    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()

  20. DIJO JOSEPH says

    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 "";
    }