用于将XML字符串转换为JSON的工具(javascript) [英] Tool (javascript) to convert a XML string to JSON
本文介绍了用于将XML字符串转换为JSON的工具(javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将XML字符串转换为JSON的最佳javascript函数/插件/库是什么?
What is the best javascript function/plugin/library to convert a XML string to JSON.
我找到了这个工具: http:// www .thomasfrank.se / xml_to_json.html ,但它不喜欢以 0
开头的字符串。即: 005321
转换为 2769
(不酷:()
I found that tool : http://www.thomasfrank.se/xml_to_json.html, but it does not like strings starting with 0
. i.e.: 005321
get converted to 2769
(not cool :( )
我的问题是,将XML转换为JSON的最佳javascript函数/插件/库是什么?
My question, what is the best javascript function/plugin/library to convert a XML to JSON?
编辑:有人试过一个工作正常吗?
EDIT : Someone tried one that works fine?
推荐答案
这个功能对我来说非常好用:
This function has worked pretty well for me:
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的工具(javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文