Parsing XML data with DOMParser

There is no longer a need to depend on server side to parse XML documents as modern web browsers  already support XML parsing and XPath evaluation. Here’s the code that demos the functionality:

try {
  var xmlDoc = (new DOMParser()).parseFromString("<data><row>1st row</row><row>2nd row</row></data>", "text/xml");
  var secondRowValue = xmlDoc.evaluate(".//data/row[2]", xmlDoc, null, XPathResult.STRING_TYPE, null).stringValue;
  alert("DOMParser works fine in your browser.\nSecond row data value is: '" + secondRowValue + "'.");
} catch (e) {
  alert("Your browser don't support DOMParser.");
}

You can check the live version here: http://perfectionlabs.com/quicks/advanced-javascript/DOMParser/

This code works fine in Firefox 1.5+, Safari 3+, and Opera 9+. Internet Explorer handles it differently but it is also possible to implement the IE compatible code, like the one here: http://erik.eae.net/archives/2005/07/03/20.19.18/.

Useful DOMParser and XPath resources can be found on XULPlanet or Mozilla MDC.

Leave a Reply