如何将xml响应映射到typescript接口

时间:2018-02-15 14:10:31

标签: javascript xml angular typescript xml2js

我正在尝试将xml响应(它使用文本XMLHttpRequestResponseType)从后端服务器映射到typescript接口。现在,我尝试使用xml2js将xml映射到JSON,然后将JSON映射到typescript接口(我正在使用Angular 5)。问题是xml2js将呈现以下内容:

假设我们有以下xml:

<xmlTag attr1="value1" attr2="value2>
    <innerTag attr3="value3">value4</innerTag>
</xmlTag>

定义接口的方式如下:

export interface XmlTag {
    attr1?: string;
    attr2?: string;
    innerTag?: InnerTag;
}

export interface InnerTag {
    attr3?: string;
    innerTagValue?: string;
}

问题是xml2js映射xml属性,其中'$'作为e键,嵌套的json对象作为其值。例如:

<xmlTag attr1="value1" attr2="value2>
    <innerTag attr3="value3">value4</innerTag>
</xmlTag>

转化为: image

因此'$'用作标记属性的键,嵌套的json对象用作值,包含所有属性,标记之间的值为'_'。

当我需要在HTML页面中绑定它时,我必须使用{{innerTag。$。attr3}}访问(例如attr3),使我的界面无用。

是否有任何方法(库可能)将响应映射到接口(每个xml标记应该是一个接口,接口的属性是xml标记属性和嵌套标记)?或者我必须手动完成它?

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为这就是你要做的事情:

// This is the interface that you want to use for that parser.
export interface Xml2Js {
  $?: {
    [key: string]: string;
  };
  innerTag?: Array<Xml2Js>;
  _?: string;
}

// This should be the relative structure of the JSON file (based on the screenshot you gave) that should let you get through the data that you need, assuming that you know the keys for the attributes ahead-of-time. Otherwise, you are going to have to write some fancy JavaScript to get all of that parsed.
const val: Xml2Js = {
  $: {
    'attr1': 'value1',
    'attr2': 'value2'
  },
  innerTag: [
    {
      $: {
        'attr3': 'value3'
      },
      _: 'value4'
    }
  ]
};