JS实现xml与json互转且基本保持原样

2019-11-8    seo达人



如果非要代码实现的话,github上一个不错的js库(X2JS):https://github.com/abdolence/x2js

自己写了demo测试了一下:



<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title></title>

</head>

<body>

</body>

<script src="js/xml2json.js" type="text/javascript" charset="utf-8"></script>

<script type="text/javascript">

var xmlText =

'<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/><mxCell id="2" value="" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1"><mxGeometry x="220" y="90" width="120" height="80" as="geometry"/></mxCell><mxCell id="3" value="" style="ellipse;whiteSpace=wrap;html=1;aspect=fixed;" vertex="1" parent="1"><mxGeometry x="410" y="110" width="80" height="80" as="geometry"/></mxCell></root></mxGraphModel>';

console.log("原始数据xml:"+xmlText);

var x2js = new X2JS();

var jsonObj = x2js.xml_str2json( xmlText );

console.log(jsonObj);

var xmlAsStr = x2js.json2xml_str( jsonObj );

console.log(xmlAsStr);

</script>

</html>

效果如下:







基本能还原,只是""变成了'',这个应该问题不大的。






分享本文至:

日历

链接

个人资料

蓝蓝 http://www.lanlanwork.com

存档