在angular4.0中将XML转换为Json?

时间:2018-03-08 07:34:18

标签: json xml angular data-conversion

我的XML

<list table='DDFieldList' id='59' used='true' type='list'>
    <item>
        <label>Please select</label>
        <data>0</data>
        <index>0</index>
        <itemId>0</itemId>
        <parentIndexId />
        <excludeSection />
    </item>

我想要这样的格式

{
  "list": {
    "-table": "DDFieldList",
    "-id": "59",
    "-used": "true",
    "-type": "list",
    "item": [
      {
        "label": "Please select",
        "data": "0",
        "index": "0",
        "itemId": "0"
      }];

并尝试将其转换为JSON,如何在angular4.0

中实现

1 个答案:

答案 0 :(得分:0)

您可以使用 xml-js 模块来实现从Xml到Json的全面转换,反之亦然。

模块: https://www.npmjs.com/package/xml-js

安装:

npm install --save xml-js

用法:

    import { xml2json } from 'xml-js';

getItemTo(){
    var xml = `<?xml version="1.0" encoding="utf-8"?><list table='DDFieldList' id='59' used='true' type='list'>
    <item>
        <label>Please select</label>
        <data>0</data>
        <index>0</index>
        <itemId>0</itemId>
        <parentIndexId />
        <excludeSection />
    </item></list>`;

    var result1 = xml2json(xml, {compact: true, spaces: 4});
    var result2 = xml2json(xml, {compact: false, spaces: 4});
    console.log(result1, '\n', result2);

return result1.list;

}