您的位置:首页 > Web前端 > JQuery

jQuery插件-JSON与XML互转

2015-12-16 20:09 621 查看
jQuery插件-JSON与XML互转
sf2gis@163.com
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

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息