jQuery插件-JSON与XML互转
2015年12月16日
1 目标:JSON与XML相互转换
2 原理:字符串与正则表达式处理。
3 流程:安装js插件,使用转换函数。
3.1 安装js:添加jQuery,json2xml,xml2json。
下载地址:http://json.cn/download/jquery.xml2json.js
http://json.cn/download/jquery.json2xml.js
参见:http://json.cn/component.html
<scripttype="text/javascript"src="jquery-1.11.3.js"></script>
<scripttype="text/javascript"src="jquery.json2xml.js"></script>
<scripttype="text/javascript"src="jquery.xml2json.js"></script>
3.2 使用转换函数
$.xml2json(xml)
$.json2xml(json,{options:value})
//jsonxml.html
<!DOCTYPEhtml>
<html>
<head>
<metacharset="UTF-8">
<title>Inserttitle here</title>
</head>
<scripttype="text/javascript"src="jquery-1.11.3.js"></script>
<scripttype="text/javascript" src="jquery.json2xml.js"></script>
<scripttype="text/javascript"src="jquery.xml2json.js"></script>
<body>
<button type="button"id="xml2json">xml2json</button >
<scripttype="text/javascript">
$(function() {
$("#xml2json").click(function(){
xml2json();
});
});
function xml2json(){
var mySoapXml ='<soap:Envelopexmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" '+
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" '+
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'+
'<soap:Bodyxmlns:lee="http://lee/"><lee:sayHello/></soap:Body></soap:Envelope>';
var json=$.xml2json(mySoapXml);
varjsonStr=JSON.stringify(json);
console.debug("json="+jsonStr);
console.debug("json="+$.parseJSON(jsonStr));
console.debug(json);
var xml=$.json2xml(json,{"rootTagName":'soap:Envelope'});
console.debug("xml="+xml);
}
</script>
</body>
</html>
结果:JSON和xml相互转换成功。
4 方法:
注意:官网为http://www.fyneworks.com/jquery/xml-to-json/ ,但是不能下载。
4.1 XML2JSON时根结点名会丢失,但属性保留。
4.2 JSON2XML时可以指定根结点的名字,默认为root。其它参数参见源码。
varxml=$.json2xml(json,{"rootTagName": 'soap:Envelope'});
对应的xml为
<soap:Envelopexmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Bodyxmlns:lee="http://lee/">
<sayHello></sayHello>
</Body>
</soap:Envelope>
参考:http://json.cn/component.html