JS實(shí)現(xiàn)xml與json互轉(zhuǎn)且基本保持原樣

2019-11-8    seo達(dá)人



如果非要代碼實(shí)現(xiàn)的話,github上一個(gè)不錯(cuò)的js庫(X2JS):https://github.com/abdolence/x2js

自己寫了demo測(cè)試了一下:



<!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("原始數(shù)據(jù)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>

效果如下:







基本能還原,只是""變成了'',這個(gè)應(yīng)該問題不大的。






分享本文至:

日歷

鏈接

個(gè)人資料

存檔