Js2XML returned extra "item" tag when converting to XML

400 views Asked by At

I'm doing typescript project using js2xml package for convert json object to xml.

Below is the xml that I need as the output.

<?xml version="1.0" encoding="UTF-8"?>
<Marks>
    <IndexNo>202104455</IndexNo>
    <IndexNo>20210488</IndexNo>
</Marks>

For that I create below interface in typescript.

export interface Subject {
    IndexNo: string[];
}

Then I assign values like below.

    let objSubject: Subject = {
      IndexNo: ["202104455", "20210488"]
    }

    var jsn = JSON.parse(JSON.stringify(objSubject));
    console.log(jsn);
    var outputXML = new Js2Xml("Marks", jsn);

Above json is,

{ IndexNo: [ '202104455', '20210488' ] }

After executing, It returned below xml. The problem is extra "item" tag appear inside indexNo tag. What I want is above mentioned xml.

<?xml version="1.0" encoding="UTF-8"?>
<Marks>
  <IndexNo>
    <item>202104455</item>
    <item>20210488</item>
  </IndexNo>
</Marks>

How to fix above issue? Is there any other npm package for doing my task?

1

There are 1 answers

0
Marc Stroebel On

I prefer using xml-js, complex but working ;-)

import { js2xml } from 'xml-js';

const objSubject = {
  declaration: { attributes: { version: '1.0', encoding: 'utf-8' } },
  elements: [
    {
      type: 'element',
      name: 'Marks',
      elements: [
        {
          type: 'element',
          name: 'IndexNo',
          elements: [{ type: 'text', text: '202104455' }],
        },
        {
          type: 'element',
          name: 'IndexNo',
          elements: [{ type: 'text', text: '20210488' }],
        },
      ],
    },
  ],
};

var outputXML = js2xml(objSubject);

console.log(outputXML.toString());

Output:

<Marks><IndexNo>202104455</IndexNo><IndexNo>20210488</IndexNo></Marks>