将 SVG 元素转换为字符串

-1 javascript jquery svg

在网页中,我已将 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>
Run Code Online (Sandbox Code Playgroud)

然后通过一些循环,我将每个节点放入一个数组中,看起来像这样:

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" />]
Run Code Online (Sandbox Code Playgroud)

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

Gen*_*e R 5

您可以outerHTML使用HtmlElement

var arr = $.map($('svg *'), function(v){ return v.outerHTML; });
Run Code Online (Sandbox Code Playgroud)

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