JavaScript: XML to strings and back again

October 2008

Since jumping on the JSON bandwagon sometime ago, I've rarely touched XML in a browser. That's not to say I have an overiding preference for either, it's just the way things have panned out.

I came across a problem at work the other day that required me to convert an XML object to a string and that string back into XML. There is nothing magical or in anyway new about this process as it's been done a million times before, but I was a little surprised at how much Googling around I had to do to remind myself of the syntax to do this in Internet Explorer. Hopefully this will save you that time I lost.

Here are my two conversion functions, maybe you'll find them useful.

function XMLToString(oXML) {
  if (window.ActiveXObject) {
    return oXML.xml;
  } else {
    return (new XMLSerializer()).serializeToString(oXML);
  }
}

function XMLFromString(sXML) {
  if (window.ActiveXObject) {
    var oXML = new ActiveXObject("Microsoft.XMLDOM");
    oXML.loadXML(sXML);
    return oXML;
  } else {
    return (new DOMParser()).parseFromString(sXML, "text/xml");
  }
}

I've tested the above in Internet Explorer 6 + 7. Firefox 2 + 3, Opera 9.5 and Safari on my XP machine, Firefox on my Ubuntu box and Firefox and Safari on my Mac.

If you're interested to see other jQuery work I've done, check out my JAWStats web analytics project.

Jon Combe