将SVG元素转换为字符串

时间:2016-03-17 07:58:04

标签: 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>

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

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

2 个答案:

答案 0 :(得分:3)

您可以使用outerHTML的{​​{1}}:

HtmlElement

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

答案 1 :(得分:1)

基因是对的。为什么不使用<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <FrameLayout android:id="@+id/pager_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:background="#CCC" android:clipChildren="false"> <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:clipChildren="false" android:layout_width="match_parent" android:layout_height="300dp" android:layout_gravity="center" android:layout_marginLeft="@dimen/dimen_50" android:layout_marginRight="@dimen/dimen_50" /> </FrameLayout> </RelativeLayout> ? 这是一个vanilla JavaScript(即没有jQuery)的解决方案:

outerHTML