javascript - 如何将 JSON 对象数组转换为有效的 XML?
问题描述
假设我有一个这样的 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>
解决方案
如果您使用 FXP (fast-xml-parser),您可以使用以下配置来避免数组索引作为标签名称
const parser = new j2xParser({
rootNodeName: "car"
});
const result = parser.parse(cars);
FXP 版本必须 > 3.21.0
推荐阅读
- google-api - 如何将谷歌文档复制到谷歌驱动服务中的另一个文件夹
- shell - 关于在 vim 命令模式下使用 shell 管道的困惑
- java - Microsoft 图形搜索功能 Java
- c - pthread_join 中的 retval 函数
- r - Edit Windows environmental variable
- excel - Excel:对列进行排序以匹配另一列的值
- python - 根据 NaN 值将数据帧拆分为多个数据帧
- java - 尝试使用另一个人使用的方法中的资源
- unity3d - 如何在 Unity 中创建一个平面,在应用程序中使用 AR 相机时始终显示该平面
- java - Spring Boot Active Directory 仅在未受保护的端点上进行验证