XML parsing of a variable string in JavaScript XML parsing of a variable string in JavaScript xml xml

XML parsing of a variable string in JavaScript


Updated answer for 2017

The following will parse an XML string into an XML document in all major browsers. Unless you need support for IE <= 8 or some obscure browser, you could use the following function:

function parseXml(xmlStr) {   return new window.DOMParser().parseFromString(xmlStr, "text/xml");}

If you need to support IE <= 8, the following will do the job:

var parseXml;if (typeof window.DOMParser != "undefined") {    parseXml = function(xmlStr) {        return new window.DOMParser().parseFromString(xmlStr, "text/xml");    };} else if (typeof window.ActiveXObject != "undefined" &&       new window.ActiveXObject("Microsoft.XMLDOM")) {    parseXml = function(xmlStr) {        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");        xmlDoc.async = "false";        xmlDoc.loadXML(xmlStr);        return xmlDoc;    };} else {    throw new Error("No XML parser found");}

Once you have a Document obtained via parseXml, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

Example usage:

var xml = parseXml("<foo>Stuff</foo>");alert(xml.documentElement.nodeName);

If you're using jQuery, from version 1.5 you can use its built-in parseXML() method, which is functionally identical to the function above.

var xml = $.parseXML("<foo>Stuff</foo>");alert(xml.documentElement.nodeName);


Update: For a more correct answer see Tim Down's answer.

Internet Explorer and, for example, Mozilla-based browsers expose different objects for XML parsing, so it's wise to use a JavaScript framework like jQuery to handle the cross-browsers differences.

A really basic example is:

var xml = "<music><album>Beethoven</album></music>";var result = $(xml).find("album").text();

Note: As pointed out in comments; jQuery does not really do any XML parsing whatsoever, it relies on the DOM innerHTML method and will parse it like it would any HTML so be careful when using HTML element names in your XML. But I think it works fairly good for simple XML 'parsing', but it's probably not suggested for intensive or 'dynamic' XML parsing where you do not upfront what XML will come down and this tests if everything parses as expected.


Most examples on the web (and some presented above) show how to load an XML from a file in a browser compatible manner. This proves easy, except in the case of Google Chrome which does not support the document.implementation.createDocument() method. When using Chrome, in order to load an XML file into a XmlDocument object, you need to use the inbuilt XmlHttp object and then load the file by passing it's URI.

In your case, the scenario is different, because you want to load the XML from a string variable, not a URL. For this requirement however, Chrome supposedly works just like Mozilla (or so I've heard) and supports the parseFromString() method.

Here is a function I use (it's part of the Browser compatibility library I'm currently building):

function LoadXMLString(xmlString){  // ObjectExists checks if the passed parameter is not null.  // isString (as the name suggests) checks if the type is a valid string.  if (ObjectExists(xmlString) && isString(xmlString))  {    var xDoc;    // The GetBrowserType function returns a 2-letter code representing    // ...the type of browser.    var bType = GetBrowserType();    switch(bType)    {      case "ie":        // This actually calls into a function that returns a DOMDocument         // on the basis of the MSXML version installed.        // Simplified here for illustration.        xDoc = new ActiveXObject("MSXML2.DOMDocument")        xDoc.async = false;        xDoc.loadXML(xmlString);        break;      default:        var dp = new DOMParser();        xDoc = dp.parseFromString(xmlString, "text/xml");        break;    }    return xDoc;  }  else    return null;}