使用 Javascript 的 JSON 到 XML
问题我正在尝试将 JSON 转换为 XML,但我没有得到确切的输出。在我的 JSON 中,它没有将其转换为 XML 数组
var InputJSON = "{"body":{"entry": [{ "fullURL" : "abcd","Resource": "1234"},{ "fullURL" : "efgh","Resource": "5678"}]}}";
var output = eval("OBJtoXML("+InputJSON+");")
function OBJtoXML(obj) {
var xml = '';
for (var prop in obj) {
xml += "<" + prop + ">";
if(obj instanceof Array) {
for (var array in obj) {
xml += OBJtoXML(new Object(obj));
}
} else if (typeof obj == "object") {
xml += OBJtoXML(new Object(obj));
} else {
xml += obj;
}
xml += "</" + prop + ">";
}
var xml = xml.replace(/<\/?{1,}>/g,'');
return xml
}
实际生产:
<body>
<entry>
<fullURL>abcd</fullURL>
<Resource>1234</Resource>
<fullURL>efgh</fullURL>
<Resource>5678</Resource>
</entry>
</body>
预期输出:
<body>
<entry>
<fullURL>abcd</fullURL>
<Resource>1234</Resource>
</entry>
<entry>
<fullURL>efgh</fullURL>
<Resource>5678</Resource>
</entry>
</body>
如果我在代码中遗漏了任何内容,请指导我达到预期的结果
回答
将 OBJtoXML 函数替换为
function OBJtoXML(obj) {
var xml = '';
for (var prop in obj) {
xml += obj instanceof Array ? '' : "<" + prop + ">";
if (obj instanceof Array) {
for (var array in obj) {
xml += "<" + prop + ">";
xml += OBJtoXML(new Object(obj));
xml += "</" + prop + ">";
}
} else if (typeof obj == "object") {
xml += OBJtoXML(new Object(obj));
} else {
xml += obj;
}
xml += obj instanceof Array ? '' : "</" + prop + ">";
}
var xml = xml.replace(/<\/?{1,}>/g, '');
return xml
}
页:
[1]