[英]How can I get rid of each element wrapped by the array key separately while converting array of object to xml?
While converting an array of object into xml, each element inside the array gets wrapped with the array key in the xml.在将对象数组转换为 xml 时,数组中的每个元素都被 xml 中的数组键包裹。 How can I make all element wrapped by the array key for once?如何使数组键包裹的所有元素一次?
the problem is for each element in the array gets wrapped by the array key separately while converting the xml.问题是数组中的每个元素在转换 xml 时分别由数组键包装。
my json is like:我的 json 是这样的:
{a:
[
{first: 1},
{second:2}
]
}
this gets converted to这被转换为
<a>
<first> </first>
</a>
<a>
<second> </second>
</a>
but what I want is但我想要的是
<a>
<first> </first>
<second> </second>
</a>
I found a solution.我找到了解决方案。
function OBJtoXML(obj) {
var xml = '';
for (var prop in obj) {
xml += obj[prop] instanceof Array ? '' : "<" + prop + ">";
if (obj[prop] instanceof Array) {
xml += "<" + prop + ">";
for (var array in obj[prop]) {
xml += OBJtoXML(new Object(obj[prop][array]));
}
xml += "</" + prop + ">";
} else if (typeof obj[prop] == "object") {
xml += OBJtoXML(new Object(obj[prop]));
} else {
xml += obj[prop];
}
xml += obj[prop] instanceof Array ? '' : "</" + prop + ">";
}
var xml = xml.replace(/<\/?[0-9]{1,}>/g, '');
return xml
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.