admin管理员组文章数量:1305542
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 but it doesn't escape the data.
How can I escape the data properly so that the browser's XML parser will work?
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./c4milo/3738875 but it doesn't escape the data.
How can I escape the data properly so that the browser's XML parser will work?
Share Improve this question edited Oct 14, 2016 at 9:16 danwellman 9,2738 gold badges63 silver badges91 bronze badges asked Nov 23, 2011 at 11:32 Andrew MAndrew M 291 gold badge1 silver badge2 bronze badges4 Answers
Reset to default 2You can try this small library http://code.google./p/x2js/
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.
Why don't you just use XML or JSON consequently?
You can use the external js available by google named x2js.js
You can see the demo over here.
jsFiddle Demo
you can use this function in your code to convert JSON to XML in js
var json2xml = function (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
so in the main
var xmlDOM = json2xml(eval(jsonObj));
var oSerializer = new XMLSerializer();
var sXML = oSerializer.serializeToString(xmlDOM);
本文标签: convert JSON object to XML using javascriptStack Overflow
版权声明:本文标题:convert JSON object to XML using javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741803634a2398370.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论