2

I am trying to map an xml response (it uses text XMLHttpRequestResponseType) from a backend server to a typescript interface. Right now, I tried to use xml2js to map the xml into a JSON and then map the JSON to the typescript interface (I am working with Angular 5). the problem is that xml2js will render the following:

Let's say we have the following xml:

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

The way that the interfaces are defined is the following:

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

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

The problm is that xml2js maps xml attributes with '$' as e key and a nested json object as its value. Example:

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

gets transformed into: image

So a '$' is used as a key for tag attributes and a nested json object as a value, containing all the attributes and a '_' for the value between the tags.

When I need to bind it inside an HTML page I have to access (for example attr3) by using {{innerTag.$.attr3}}, rendering my interface useless.

Is there any way (library maybe) to map the response to the interface (every xml tag should be an interface and the interfaces' attributes being the xml tag attributes and the nested tags)? Or I have to manually do it?

Thank you!

  • please post the code instead of the image, it's a lot easier to read. – toskv Feb 15 '18 at 14:25
  • I don't know about xml2js, but I think you can always transform a "string" in an object like I try to do in https://stackoverflow.com/questions/48596404/angular-2-5-service-with-httpclient-makes-mistake-and-doesnt-works – Eliseo Feb 15 '18 at 14:26

1 Answers1

-1

I think this is what you are trying to do:

// 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'
    }
  ]
};
th3n3wguy
  • 3,649
  • 2
  • 23
  • 30