Convert DOM Node or Document to XML in JavaScript

Say that one single DOM or Document element (like window.document) is passed to you in JavaScript, how would you turn this into valid XML?

In particular, for my example, I have a webpage with SVG mapping, this SVG has a lot of JavaScript to let you interact. This is a graphical display that allows you to scale the graph and even make some conversions. Now users with this want to have a "Save Image" button. I suppose that this is done to take the node document for the SVG element and convert it to XML, and then send it to the server, which then returns the page with the SVG document or PNG image.

This all works on FireFox (which is currently a requirement for users, although it works great in both Safari and Chrome). In firefox on a webpage, I included the SVG document as an Object element. In javascript, I can access these contentDocument objects, which refers to the root of the XML page. It contains an XML version, a Document tag, and a svg root tag with all attributes.

Perhaps someone has already decided this, so I can copy their code. Perhaps someone knows where to look in firebug to achieve this. Or perhaps there are DOM methods for this.

+3
source share
2 answers

API: XMLSerializer ( , , IE).

serializeToString DOMNode.

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

Internet Explorer XML HTML, .outerHTML , HTML (, , ..).

+4

XMLSerializer . , , , - ( FireBug ):

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+"\">"
}
+1

Source: https://habr.com/ru/post/1707766/


All Articles