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 = newXMLSerializer().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):

functionextractXML(node) {
    switch (node.nodeType) {
        case1: return extractNodeXML(node);
        case2: return extractAttributeXML(node);
        // 3 = Text nodecase3: return node.nodeValue;
        // 8 = Comment node - ignorecase8: return"";
        case9: return extractDocumentNodeXML(node);
        case10: return extractDocumentTypeXML(node);
        default: console.log(node); return"Unkwon type: "+node.nodeType;
    }
}
functionextractNodeXML(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;
}
functionextractAttributeXML(node) {
    return node.nodeName+"=\""+node.nodeValue+"\""
}
functionextractDocumentNodeXML(node) {
    var xml = "<?xml version=\""+node.xmlVersion+"\" encoding=\""+node.xmlEncoding+"\"?>"$A(node.childNodes).each(function (node) {xml += extractXML(node)});
    return xml;
}
functionextractDocumentTypeXML(node) {
    return"<!DOCTYPE "+node.name+" PUBLIC \""+node.publicId+"\" \""+node.systemId+"\">"
}

Post a Comment for "Convert A Dom Node Or Document To Xml In Javascript"