How to Parse XML with jQuery Cross-Browser

Parsing XML data across different web browsers can often introduce compatibility challenges due to varying implementations of browser parsers, such as the standard DOMParser and Internet Explorer's legacy ActiveXObject. jQuery simplifies this process significantly by providing the built-in $.parseXML() utility, which standardizes XML string parsing into a single, uniform method that works reliably across all browsers. This article explains how to parse raw XML strings using $.parseXML(), handle XML retrieved via AJAX requests, traverse and extract data using standard jQuery DOM methods, and manage parsing errors gracefully.

Parsing an XML String with $.parseXML()

To convert a raw XML string into a queryable XML Document object, use jQuery's native $.parseXML() function. Once the XML is parsed into a document object, pass it into the main jQuery wrapper $(...) to traverse and manipulate it using standard jQuery traversal methods like .find(), .text(), and .attr().

// Sample XML string
var xmlData = 
  '<catalog>' +
    '<book id="bk101">' +
      '<title>JavaScript: The Good Parts</title>' +
      '<author>Douglas Crockford</author>' +
      '<price>29.99</price>' +
    '</book>' +
    '<book id="bk102">' +
      '<title>Eloquent JavaScript</title>' +
      '<author>Marijn Haverbeke</author>' +
      '<price>24.95</price>' +
    '</book>' +
  '</catalog>';

// Parse the string into an XML DOM document
var xmlDoc = $.parseXML(xmlData);

// Wrap the XML DOM in jQuery to enable standard DOM navigation
var $xml = $(xmlDoc);

// Extract data from the parsed XML
$xml.find('book').each(function() {
    var id = $(this).attr('id');
    var title = $(this).find('title').text();
    var author = $(this).find('author').text();
    var price = $(this).find('price').text();

    console.log(`[${id}] ${title} by ${author} - $${price}`);
});

Parsing XML Fetched via AJAX

If the XML data is hosted externally or stored in a separate file, you do not need to call $.parseXML() explicitly. By setting the dataType parameter to "xml" in an $.ajax() call, jQuery automatically parses the incoming response into an XML DOM before passing it to the success callback.

$.ajax({
    type: "GET",
    url: "catalog.xml",
    dataType: "xml",
    success: function(xml) {
        $(xml).find('book').each(function() {
            var title = $(this).find('title').text();
            console.log("Book Title: " + title);
        });
    },
    error: function(xhr, status, error) {
        console.error("Failed to load or parse XML:", error);
    }
});

Handling Malformed XML and Errors

If the supplied XML string is malformed or invalid, $.parseXML() will throw a JavaScript error across modern browsers. To prevent unexpected application crashes, wrap $.parseXML() within a try...catch block.

var malformedXml = '<catalog><book><title>Missing closing tag</book>';

try {
    var xmlDoc = $.parseXML(malformedXml);
    var $xml = $(xmlDoc);
    console.log("XML parsed successfully.");
} catch (error) {
    console.error("Invalid XML: Unable to parse.", error.message);
}

Extracting Attributes and Node Values

Navigating an XML structure with jQuery utilizes the same methods used for HTML DOM manipulation:

  • .find("tagName"): Locates child elements matching the specified tag name.
  • .text(): Retrieves the plain text content contained within an element.
  • .attr("attributeName"): Retrieves the value of a specific XML attribute on the selected element.
  • .each(callback): Iterates over a collection of matched XML nodes.