将 SVG 元素转换为字符串

Converting an SVG element to string

本文关键字:字符串 转换 元素 SVG      更新时间:2023-09-26

在网页中,我将SVG文件加载到div中,如下所示:

<svg id="svg" width="500px" height="500px">
    <g id="1">
        <rect id="0" x="50" y="25" width="50px" height="50px" style="fill:blue;"/>
        <rect id="2" x="110" y="125" width="50px" height="50px" style="fill:blue;"/>
    </g>
    <g id="2">
        <circle id="2" cx="150" cy="50" r="40"  stroke-width="4"  />
        <polygon id="3" points="200,10 250,190 160,210" style="stroke-width:1" />
    </g>
</svg>

然后通过一些循环,我将每个节点放入一个数组中,如下所示:

array[<g id="1"></g>,<rect id="0" x="50" y="25" width="50px" height="50px" style="fill:blue;"/>, <rect id="2" x="110" y="125" width="50px" height="50px" style="fill:blue;"/>, <g id="2"><circle id="2" cx="150" cy="50" r="40"  stroke-width="4"/>,<polygon id="3" points="200,10 250,190 160,210" style="stroke-width:1" />]

这里的问题是将它们存储为对象,我希望它存储为字符串,我已经在任何对象上尝试过 JSON.stringify 之类的东西,但到目前为止没有运气。我正在使用javascript和jQuery

您可以使用HtmlElement outerHTML

var arr = $.map($('svg *'), function(v){ return v.outerHTML; });

示例:https://jsbin.com/qijicibime/edit?html,js,output

Gene 是对的。为什么不使用outerHTML?这是vanilla JavaScript中的一个解决方案(即没有jQuery):

var nodesHTML = [].slice.call( document.querySelectorAll("svg *") ).map(
    function( node ) { return node.outerHTML; });