json - Angular:将 2D json 对象转换为 XML
问题描述
我正在使用以下代码将 2D 数组转换为 json 并将 json 转换为 XML:
export class Son
{
public d : number;
public e : number[][];
constructor (){
this.e = new Array (16);
for (let i=0;i<16;i++)
this.e[i] = new Array(2);
}
}
export class Father
{
public a : number;
public b : number;
public c : Son;
constructor (){
this.c = new Son();
}
}
var xml2js = require('xml2js');
var builder = new xml2js.Builder();
var a_obj = new Father();
a_obj.a=1;
a_obj.b=2;
a_obj.c.d=3;
a_obj.c.e[0][0]=1;
a_obj.c.e[0][1]=1;
var a_json = JSON.parse(JSON.stringify(a_obj));
var a_xml = builder.buildObject(a_json);
如果对象 (a_obj) 不包含二维数组,则可以正常工作。但就我而言,我得到了以下 xml 字符串:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<c>
<e/>
<e/>
<e/>
<e/>
<e/>
<e/>
<e/>
<e/>
<e/>
<e/>
<e/>
<e/>
<e/>
<e/>
<e/>
<e/>
<d>3</d>
</c>
<a>1</a>
<b>2</b>
</root>
预先感谢您的回复。兹维卡
解决方案
你觉得这个功能怎么样:
function object2Xml(obj, tag='xml', attributes={}) {
var inner = '';
if (typeof (obj) === 'string') {
inner = obj;
} else if (typeof (obj) === 'number') {
inner = obj;
} else if (typeof (obj) === 'boolean') {
inner = obj;
} else if (typeof (obj) === 'function') {
return '';
} else if (typeof (obj) === 'object') {
if (Array.isArray(obj)) {
return obj.map((v)=>object2Xml(v, tag, {array: true})).join('')
} else {
if (tag==='xml' && obj.constructor.name!=='Object') {
tag = obj.constructor.name
}
Object.keys(obj).forEach(key=>{
inner += object2Xml(obj[key], key)
});
}
}
var attr = '';
Object.keys(attributes).forEach(key=>{
attr += ' '+key + '=' + '"'+attributes[key]+'"';
});
return '<' + tag + attr + '>' + inner + '</' + tag + '>'
}
你可以像object2Xml(a_obj);
.
要知道,将对象转换为 xml 的方法不止一种,需要做出很多决定,js 中的属性是否应该成为属性或字符串值,如果数组被包装到额外的标签中,......但是上面的函数可能会给你一个起点。
推荐阅读
- java - JavaFX - 更改颜色后,TextField 提示文本不会在焦点时被删除
- vba - 从今天下载 .csv 附件
- c++ - c ++ while循环计时器的准确性变化很大
- ruby - 离线验证签名数据保险库
- android - AnimatorSet 和 Object/ValueAnimator 的持续时间有什么区别?
- java - 查找被点击视图的 ID 或标签
- amazon-web-services - 哪个服务的响应时间较短?SQS 与 DynamoDB
- java - 如何读取或打印 BufferedReader (InputStreamReader)
- vue.js - 为什么未定义具有道具初始值的数据中声明的字段?
- google-cloud-platform - 谷歌云站点在安装 2 小时后出现“504 网关错误”