Jquery 实现xml转json

来源:互联网 发布:淘宝三包图片 编辑:程序博客网 时间:2024/05/17 03:30

代码

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>        <script src="js/jquery.min.js" type="text/javascript" charset="utf-8"></script>    </head>    <body>    </body></html><script type="text/javascript">    function fozzz(myXml, myJson) {        $(myXml).each(function() {            //新节点            var tempJson = {}            //节点的属性            var tempJsonSon = {}            //节点的孩子节点            var tempArr = []            //节点名字            tempJson[this.nodeName] = tempJsonSon            //节点属性            attrs = this.attributes            for(i = 0; i < attrs.length; i++) {                tempJsonSon[attrs[i].nodeName] = attrs[i].nodeValue            }            //没有子节点,直接输出文本            if($(this).children().length == 0) {                tempJsonSon["text"] = $(this).text()            } else {                //有子节点,嵌套循环                tempJsonSon["son"] = tempArr                fozzz($(this).children(), tempArr)            }            //添加到一个数组中            myJson.push(tempJson)        })    }    $.get("china.xml", function(myXml) {        //结果数组        myJson = []        //实现方法        fozzz(myXml.firstChild, myJson)        //输出json格式内容        document.write(JSON.stringify(myJson))    })</script>

结果

-----------xml----------------<china>    <province name="四川省">        <city>成都</city>        <city>绵阳</city>    </province>    <province name="吉林省">        <city>长春</city>        <city>吉林市</city>    </province></china>
----------json-------------[    {        "china": {            "son": [                {                    "province": {                        "name": "四川省",                        "son": [                            {                                "city": {                                    "text": "成都"                                }                            }, {                                "city": {                                    "text": "绵阳"                                }                            }                        ]                    }                }, {                    "province": {                        "name": "吉林省",                        "son": [                            {                                "city": {                                    "text": "长春"                                }                            }, {                                "city": {                                    "text": "吉林市"                                }                            }                        ]                    }                }            ]        }    }]

网站验证
这里写图片描述

0 0
原创粉丝点击