首页 > 解决方案 > 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>

预先感谢您的回复。兹维卡

标签: jsonangularxml

解决方案


你觉得这个功能怎么样:

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 中的属性是否应该成为属性或字符串值,如果数组被包装到额外的标签中,......但是上面的函数可能会给你一个起点。


推荐阅读