Skip to content Skip to sidebar Skip to footer

Convert A DOM Node Or Document To XML In JavaScript

Say you in JavaScript are handed a single DOM element or Document (for example window.document), how would you turn that into valid XML? More specifically for my example, I have a

Solution 1:

There is a non-standard API object: XMLSerializer (it is not standard though is implemented in all but IE browsers).

Its serializeToString method expects DOMNode object to be passed.

var sXML = new XMLSerializer().serializeToString(document.body);

In Internet Explorer there is no way to retrieve proper XML for HTML, unless getting .outerHTML and fixing all problems that come with serialization to HTML (such as missing quotes in attributes, not closed tags etc.)


Solution 2:

I will have to look into XMLSerializer tomorrow. Here is the code I ended up writing instead, in case anyone is interested (requires prototype and FireBug for unknown nodes):

function extractXML(node) {
    switch (node.nodeType) {
        case 1: return extractNodeXML(node);
        case 2: return extractAttributeXML(node);
        // 3 = Text node
        case 3: return node.nodeValue;
        // 8 = Comment node - ignore
        case 8: return "";
        case 9: return extractDocumentNodeXML(node);
        case 10: return extractDocumentTypeXML(node);
        default: console.log(node); return "Unkwon type: "+node.nodeType;
    }
}
function extractNodeXML(node) {
    var xml = "<"+node.nodeName;
    $A(node.attributes).each(function (node) {xml += " "+extractXML(node)});
    xml +=">"
    $A(node.childNodes).each(function (node) {xml += extractXML(node)});
    xml += "</"+node.nodeName+">"
    return xml;
}
function extractAttributeXML(node) {
    return node.nodeName+"=\""+node.nodeValue+"\""
}
function extractDocumentNodeXML(node) {
    var xml = "<?xml version=\""+node.xmlVersion+"\" encoding=\""+node.xmlEncoding+"\"?>"
    $A(node.childNodes).each(function (node) {xml += extractXML(node)});
    return xml;
}
function extractDocumentTypeXML(node) {
    return "<!DOCTYPE "+node.name+" PUBLIC \""+node.publicId+"\" \""+node.systemId+"\">"
}

Post a Comment for "Convert A DOM Node Or Document To XML In JavaScript"