首页 > 解决方案 > 如何将类型化数组的打字稿对象解析为xml,包括数组对象名称

问题描述

我正在尝试将PersonTypescript 对象转换为 XML,但转换中不包含“CAR”标签,我该如何实现?

已经尝试使用库 js2xmlparser 和 xml-js,使用 Angular 8 并尝试使用 JSON.Stringify() 但在 JSON 中出现相同的结果,Typescript 数组被编码而没有嵌套在其中的对象的名称。

export class Person {
  ...
  CarsList: Car[];

  constructor() {
    this.CarsList = [];
  }

}
export class Car {
  ...
  Parts: Parts[];
  Model: string;
  ...
}

我实际用于编码为 xml 的代码如下:


import * as xmlJs from 'xml-js';

// This is using the xml-js library to generate the xml in the return 
getWithXmlJsLibrary(obj: Person) {
   const options = { compact: true, ignoreComment: true, spaces: 4 };
   return xmlJs.js2xml(obj, options);     // js2xml
  }

预期结果是

<Person>
    <CarsList>
       <Car>
         <Model>value</Model>
       </Car>
       <Car>
         <Model>value</Model>
       </Car>
       <Car>
         <Model>value</Model>
       </Car>
    </Carslist>
</Person>

但实际结果是

<Person>
    <CarsList>
         <Model>value</Model>
         <Model>value</Model>
         ...
    </Carslist>
</Person>

标签: javascriptxmlangulartypescriptlibxml-js

解决方案


推荐阅读