使用 javascript 将 JSON 对象转换为 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8241447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert JSON object to XML using javascript
提问by Andrew M
I want to convert a JSON object to a XML String and I can't figure a proper way to do it. I've found a neat little jQuery plugin called json2xml at https://gist.github.com/c4milo/3738875but it doesn't escape the data.
我想将一个 JSON 对象转换为一个 XML 字符串,但我想不出正确的方法来做到这一点。我在https://gist.github.com/c4milo/3738875 上找到了一个名为 json2xml 的简洁的 jQuery 插件,但它没有转义数据。
How can I escape the data properly so that the browser's XML parser will work?
如何正确转义数据以便浏览器的 XML 解析器可以工作?
回答by abdolence
You can try this small library http://code.google.com/p/x2js/
你可以试试这个小库http://code.google.com/p/x2js/
回答by user2174794
You can use the external js available by google named x2js.js
您可以使用 google 提供的名为 x2js.js 的外部 js
You can see the demo over here.
你可以在这里看到演示。
回答by Has QUIT--Anony-Mousse
There is no unique way of doing this. You should be using XML with a schema only, and JSON doesn't have such a schema. Any such transformation when done naively is likely to break.
没有独特的方法可以做到这一点。您应该仅将 XML 与架构一起使用,而 JSON 没有这样的架构。如果天真地进行任何此类转换,则可能会中断。
Why don't you just use XML or JSON consequently?
为什么不直接使用 XML 或 JSON?
回答by user13032776
you can use this function in your code to convert JSON to XML in js
您可以在代码中使用此函数将 JSON 转换为 js 中的 XML
var json2xml = function (o) {
var json2xml = 函数 (o) {
var tab = "\t";
var toXml = function (v, name, ind) {
var xml = "";
if (v instanceof Array) {
for (var i = 0, n = v.length; i < n; i++)
xml += ind + toXml(v[i], name, ind + "\t") + "\n";
}
else if (typeof (v) == "object") {
var hasChild = false;
xml += ind + "<" + name;
for (var m in v) {
if (m.charAt(0) == "@")
xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
else
hasChild = true;
}
xml += hasChild ? ">" : "/>";
if (hasChild) {
for (var m in v) {
if (m == "#text")
xml += v[m];
else if (m == "#cdata")
xml += "<![CDATA[" + v[m] + "]]>";
else if (m.charAt(0) != "@")
xml += toXml(v[m], m, ind + "\t");
}
xml += (xml.charAt(xml.length - 1) == "\n" ? ind : "") + "</" + name + ">";
}
}
else {
xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">";
}
}
return xml;
};
you get XML DOM in return, which in return you need to serialize
你得到 XML DOM 作为回报,作为回报,你需要序列化
so in the main
所以主要
var xmlDOM = json2xml(eval(jsonObj));
var oSerializer = new XMLSerializer();
var sXML = oSerializer.serializeToString(xmlDOM);