最近有个前端的需求: 解析后台xml, 并添加删除和修改, 然后传给后台, 思来想去, 最简单的办法就是利用xml和对象互转, 即从后台读取xml传到前台并形成表格(已有代码,或者用对象生成表格), 前台可编辑表格(包括添加,删除),提交时将表格数据存入对象中, 转为json, 再转为xml,最后以字符串形式传给后台写入文件.
逻辑图:
代码:
<html>
<body><script type&#61;"text/Javascript">
var xml &#61; "123NothingSomething";
var parseXMLJSON &#61; {parse2json: function(xmlStr){var root &#61; document.createElement(&#39;XMLROOT&#39;);root.innerHTML &#61; xmlStr;return this.parse(root);} ,parse: function(node){var result &#61; {};for(var i &#61; 0 ; i if(node.childNodes[i].nodeType&#61;&#61;1){result[node.childNodes[i].nodeName.toLowerCase()] &#61; this.parse(node.childNodes[i]);}else if(node.childNodes[i].nodeType&#61;&#61;3){return node.childNodes[i].nodeValue;}}return result;} ,parse2xml: function(data){var xmldata &#61; &#39;&#39;;for(var i in data){xmldata&#43;&#61; &#39;<&#39;&#43;i&#43;&#39;>&#39;;if(typeof data[i]&#61;&#61;&#39;object&#39;){xmldata&#43;&#61; this.parse2xml(data[i]);}else{xmldata&#43;&#61; data[i];}xmldata&#43;&#61; &#39;&#39;&#43;i&#43;&#39;>&#39;;}return xmldata;}
};
var jsonData &#61; parseXMLJSON.parse2json(xml);
var xmlData &#61; parseXMLJSON.parse2xml(jsonData);
alert(&#39;xml to json: &#39; &#43; JSON.stringify(jsonData));
alert(&#39;json to xml: &#39; &#43; xmlData);
script>body>
html>