繁体   English   中英

使用缩进序列化动态创建的html

[英]serializing dynamically created html with indentation

在使用appendChild()在html文档中创建了一堆元素之后,我试图将修改后的页面保存在客户端上。 将其发送到服务器似乎没有必要,所以我选择了:

var save = document.createElement("a");

save.classList.add("button");
save.textContent = "save";
save.download = "layout-save.html"
save.onclick = function(event) {
    var output = [];

    // serialize document to output

    var file = new window.Blob(output,{type:"text/html"});
    save.href = window.URL.createObjectURL(file);
}

document.body.appendChild(save);

但是,新创建的元素当然不会缩进。 我一直在看js-beautify,但我也注意到有关解析和序列化mozilla页面声称可以使用treewalker。

有人知道我会怎么做吗? 否则,将有一种方法可以在没有子节点的情况下序列化节点,以运行如下所示的递归循环:

var output = [];
var serializer = new XMLSerializer();

function indent(node) {
    var ancestor = node;

    while (ancestor != document.documentElement) {
        output.push("   ");
        ancestor = ancestor.parentNode;
    }

    output.push(/* serialize node tagname + attributes */);
    output.push("\n");

    for (let child of node.children) {
        indent(child);
    }

    output.push(/* node closing tag*/);
}

indent(document.documentElement);

不要犹豫告诉我,如果我在错误的树上吠叫,并感谢您的宝贵时间。

通过回答我自己的问题,您可以序列化浅表克隆以获取节点的开始和结束标签:

var save = document.createElement("a");

save.classList.add("button");
save.textContent = "save";
save.download = "layout.html"
save.onclick = function(event) {
    document.body.removeChild(save);

    var output = [];
    var serializer = new XMLSerializer();

    function indent(node) {
        function offset(node) {
            var count = 0;
            var ancestor = node;

            while (ancestor != document.documentElement) {
                count++;
                ancestor = ancestor.parentNode;
            }
            return "\t".repeat(count);
        }

        var buffer = offset(node);
        var nodeClone = serializer.serializeToString(node.cloneNode(false)).replace(' xmlns="http://www.w3.org/1999/xhtml"',"");

        if (node.children.length) {
            let tagSplit = nodeClone.replace(/(<.+>)(<\/.+>)/,"$1<!--children-->$2").split("<!--children-->");

            output.push(buffer + tagSplit[0] + "\n");

            for (let child of node.children) {
                indent(child);
            }

            output.push(buffer + tagSplit[1] + "\n");
        } else {
            output.push(buffer + nodeClone + "\n");
        }
    }

    indent(document.documentElement);

    var file = new window.Blob(output,{type:"text/html"});
    save.href = window.URL.createObjectURL(file);
}

document.body.appendChild(save);

手动删除xhtml命名空间有点可惜,但是由于它是XMLSerializer,所以我看不到任何解决方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM