假设我有一个像这样的 JSON 对象数组:
const cars = [
{
"color": "purple",
"type": "minivan",
"registration": "2020-02-03",
"capacity": 7
},
{
"color": "orange",
"type": "SUV",
"registration": "2021-05-17",
"capacity": 4
},
{
"color": "green",
"type": "coupe",
"registration": "2019-11-13",
"capacity": 2
}
];
我想将此对象转换为有效的 XML。但是我在转换时使用开始标记作为数组索引的帮助程序包,因此生成的 XML 无效。
例如:(function json2xml
来自gossner)
function json2xml(o, tab) {
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;
}, xml="";
for (var m in o)
xml += toXml(o[m], m, "");
return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, "");
}
const cars = [
{
"color": "purple",
"type": "minivan",
"registration": "2020-02-03",
"capacity": 7
},
{
"color": "orange",
"type": "SUV",
"registration": "2021-05-17",
"capacity": 4
},
{
"color": "green",
"type": "coupe",
"registration": "2019-11-13",
"capacity": 2
}
];
console.log(json2xml(cars, ' '));
我尝试了xml2js、fast-xml-parser和jstoxml包。结果是一样的。
编辑:
预期的 XML:
<element>
<color>purple</color>
<type>minivan</type>
<registration>2020-02-03</registration>
<capacity>7</capacity>
</element>
<element>
<color>orange</color>
<type>SUV</type>
<registration>2021-05-17</registration>
<capacity>4</capacity>
</element>
<element>
<color>green</color>
<type>coupe</type>
<registration>2019-11-13</registration>
<capacity>2</capacity>
</element>
这个怎么样?
这假设 JSON 对象数组都具有相同的键。
let xml = "";
const prefixXML = `<?xml version="1.0" encoding="UTF-8"?>\n<cars>\n`;
const suffixXML = "\n</cars>";
const keys = Object.keys(cars[0]);
cars.forEach((car) => {
let valueXML = keys
.map((key) => {
return `<${key}>${car[key]}</${key}>`;
})
.join("\n\t");
xml += `
<car>
${valueXML}
</car>
`;
});
const final = prefixXML + xml + suffixXML;
console.log(final);
XML 输出是:
<?xml version="1.0" encoding="UTF-8"?>
<cars>
<car>
<color>purple</color>
<type>minivan</type>
<registration>2020-02-03</registration>
<capacity>7</capacity>
</car>
<car>
<color>orange</color>
<type>SUV</type>
<registration>2021-05-17</registration>
<capacity>4</capacity>
</car>
<car>
<color>green</color>
<type>coupe</type>
<registration>2019-11-13</registration>
<capacity>2</capacity>
</car>
</cars>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句