将XML字符串转换为JSON的最佳javascript函数/插件/库是什么?
我找到了那个工具:http://www.thomasfrank.se/xml_to_json.html,但它不喜欢以0
开头的字符串。例如:005321
get转换为2769
(不酷:( )
我的问题是,将XML转换为JSON的最佳javascript函数/插件/库是什么?
编辑:有人试过一个工作正常的?
发布于 2011-10-14 16:02:13
这个函数对我来说运行得很好:
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
发布于 2011-12-09 13:27:04
另一个用于XML <=> JSON的小型库是https://github.com/abdmob/x2js。
发布于 2011-10-14 16:06:48
如果你愿意使用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"]}
https://stackoverflow.com/questions/7769829
复制