将XML字符串转换为JSON的工具(javascript)

Tool (javascript) to convert a XML string to JSON

本文关键字:工具 javascript JSON XML 字符串 转换      更新时间:2023-09-26

将XML字符串转换为JSON的最佳javascript函数/插件/库是什么?

我找到了这个工具:http://www.thomasfrank.se/xml_to_json.html,但它不喜欢以0开头的字符串。即:005321转换为2769(不冷:()

我的问题,什么是最好的javascript函数/插件/库转换XML到JSON?

编辑:有人试过一个工作良好?

这个函数对我来说工作得很好:

xmlToJson = function(xml) {
    var obj = {};
    if (xml.nodeType == 1) {                
        if (xml.attributes.length > 0) {
            obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    } else if (xml.nodeType == 3) { 
        obj = xml.nodeValue;
    }            
    if (xml.hasChildNodes()) {
        for (var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName;
            if (typeof (obj[nodeName]) == "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if (typeof (obj[nodeName].push) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                obj[nodeName].push(xmlToJson(item));
            }
        }
    }
    return obj;
}
实现:

var jsonText = JSON.stringify(xmlToJson(xmlDoc)); // xmlDoc = xml dom document

另一个用于XML <=> JSON的小库是https://github.com/abdmob/x2js

如果你愿意使用jQuery,这里有:

http://www.fyneworks.com/jquery/xml-to-json/

$.get("http://jfcoder.com/test.xml.php", function(xml){
    var json = $.xml2json(xml);
    $('pre').html(JSON.stringify(json)); // To show result in the browser
});
使用:

<nums>
 <num>00597</num>
 <num>0059</num>
 <num>5978</num>
 <num>5.978</num>
</nums>

输出:

{"num":["00597","0059","5978","5.978"]}
http://jfcoder.com/test.php