S
S
Sashqa2019-11-19 10:52:39
JavaScript
Sashqa, 2019-11-19 10:52:39

How to convert object to xml?

There is such an object:

let objXML = {
  InsuranceCompany: 'NAME',
  UsageStart: '2019',
  VehicleYear: '2019',
  Mark: 'audi',
  Model: 'a6',
  Modification: {
    Power: '180',
  }
}


I need to iterate over it and compose xml based on it:
<ns1:UsageStart>2018-09-04</ns1:UsageStart>
<ns1:VehicleYear>2019</ns1:VehicleYear>
<ns1:Mark>AUDI</ns1:Mark>
<ns1:Model>A6</ns1:Model>
<ns1:Modification>
    <ns1:Power>180</ns1:Power>
</ns1:Modification>


I tried to do it this way:
let xml = '';
const parseXML = (obj) =>
  Object.assign({}, ...Object.entries(obj).map(([ key, value ]) =>
    {
      if(value instanceof Object)  {
        parseXML(value)
      } else {
        xml += `<ns1:${key}>${value}</ns1:${key}>`
      }
    }
));
parseXML(objXML);


But I get a little not what I need - the Modification is lost:
<ns1:InsuranceCompany>NAME</ns1:InsuranceCompany>
<ns1:UsageStart>2019</ns1:UsageStart>
<ns1:VehicleYear>2019</ns1:VehicleYear>
<ns1:Mark>audi</ns1:Mark>
<ns1:Model>a6</ns1:Model>
<ns1:Power>180</ns1:Power>


How to fix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-11-19
@Sashqa

const createXML = obj => Object
  .entries(obj)
  .map(([ k, v ]) => `<ns1:${k}>${v instanceof Object ? createXML(v) : v}</ns1:${k}>`)
  .join('');

UPD. If you need line breaks and indents, then
const createXML = (obj, tabSize = 2, depth = 0) => {
  const indent = ' '.repeat(tabSize * depth);
  return Object.entries(obj).map(([ k, v ]) =>
    indent +
    `<ns1:${k}>${
      v instanceof Object
        ? `\n${createXML(v, tabSize, depth + 1)}\n${indent}`
        : v
    }</ns1:${k}>`
  ).join('\n');
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question