The Linux Page

Convert XML tags and text to a String

Today I started testing a lot of my JavaScript / jQuery code from a website I am building for a customer. I got an error, at some point, saying:

SCRIPT5007: Unable to get property 'replace' of undefined or null reference

The error was in link with the 'replace' function being referenced on an innerHTML of an element. More specifically, one of those XML element (probably the top most one.)

The fact is that Internet Explorer does not support innerHTML in an XML document. Not to be too surprised about that, XML is not HTML so there is really no reason why innerHTML should be defined on an XML document. ONly that means the jQuery.html() function is not supported to convert XML back to a string as in:

xml = jQuery.parseXML("<?xml version='1.0'?><test>...</test>");
string = xml.html();

That works perfectly under Firefox, but in Internet Explorer you get the error as shown up there.

The solution is to use the browser specific function that converts XML documents back to a string. I wrote such a function in snapwebsites and it looks like this:

snapwebsites.xmlToString = function(xml_object) // static
        // Internet Explorer
        return xml_object.xml();

    return (new XMLSerializer()).serializeToString(xml_object);

That works as expected in all browsers. The XMLSerializer may work in newer versions of Internet Explorer, but this is what I've found to work properly thus far (IE11) and I would imagine that we'll be good for a while.