Answer the question
In order to leave comments, you need to log in
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',
}
}
<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>
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);
<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>
Answer the question
In order to leave comments, you need to log in
const createXML = obj => Object
.entries(obj)
.map(([ k, v ]) => `<ns1:${k}>${v instanceof Object ? createXML(v) : v}</ns1:${k}>`)
.join('');
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 questionAsk a Question
731 491 924 answers to any question