Skip to content Skip to sidebar Skip to footer

Javascript: Replacement For Xmlserializer.serializetostring()?

I'm developing a website using the Seam framework and the RichFaces AJAX library (these isn't really all that important to the problem at hand - just some background). I seem to ha

Solution 1:

In IE you can simply use the xml property of the XML node, provided newnode really is an XML node rather than an HTML node:

functionserializeXmlNode(xmlNode) {
    if (typeofwindow.XMLSerializer != "undefined") {
        return (newwindow.XMLSerializer()).serializeToString(xmlNode);
    } elseif (typeof xmlNode.xml != "undefined") {
        return xmlNode.xml;
    }
    return"";
}

oldnode.outerHTML = serializeXmlNode(newnode);

Update following question update

I wouldn't use outerHTML to replace an element. It's not universally supported. Instead, you could use a mix of innerHTML and standard DOM methods as follows:

var tempEl = document.createElement("div");
tempEl.innerHTML = serializeXmlNode(newnode);
oldnode.parentNode.replaceChild(oldnode, tempEl.firstChild);

Solution 2:

I've since discovered the reason (a while ago actually). It turns out that IE semi-validates (it'll balk at some errors but ignore others) inserted HTML. It was throwing some 'unknown error' or something similar which was pretty much completely useless since it gave no indication as to what went wrong - just that something went wrong.

In my case, it was because an <li /> was being inserted with a parent . If you're having similar issues, you may want to make sure you're not trying to be too clever with your HTML.

Solution 3:

The suggested solution does not work for me. Here is my solution to this problem.

I replaced the line:

oldnode.outerHTML = new XMLSerializer().serializeToString(newnode);

by this:

if(navigator.appName.indexOf('Internet Explorer')>0){
    oldnode.outerHTML = newnode.xml
}else{
    oldnode.outerHTML = new XMLSerializer().serializeToString(newnode); 
}

Solution 4:

Edge case answer (mostly so I can find it later):

Sending HTML document as String to api to generate PDFs.

For anyone that needs to convert the document.body to a String and them submit it via a POST to a service to convert the document to a PDF - IE8 doesn't support XMLSerializer. That being said you can use: $(document.body).html(); for IE8.

/**
 * Decides the method by which to turn the document.body into a string that we can post to the PDF Api.
 * Most browsers support XMLSerializer, for others (ie8) use jquery's html method to generate a string.
 * @paramxmldom - document.body
 * @return - string representation of the document body
 */functionserializeXml(xmldom){
    if (typeofXMLSerializer != "undefined"){
        return (newXMLSerializer()).serializeToString(xmldom);
    } else {
        return $(xmldom).html();
    }
}

Call it with: var dom = serializeXml(document.body);

Post a Comment for "Javascript: Replacement For Xmlserializer.serializetostring()?"