Convert array top xml putting leading new line
Here is an example of how you can convert an array to XML in JavaScript, with a leading newline character:
const arr = ['item1', 'item2', 'item3'];
const xml = '<?xml version="1.0" encoding="UTF-8"?>\n';
xml += '<root>\n';
arr.forEach((item) => {
xml += ` <item>${item}</item>\n`;
});
xml += '</root>\n';
console.log(xml);
This will output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<item>item1</item>
<item>item2</item>
<item>item3</item>
</root>
Note that I used the forEach
method to iterate over the array and add each item to the XML string. I also used template literals to insert the item values into the XML string.
Alternatively, you can use a library like xml-js
to convert the array to XML:
const xml = require('xml-js');
const arr = ['item1', 'item2', 'item3'];
const xmlString = xml.toxml({
value: arr,
rootName: 'root',
elementName: 'item'
});
console.log(xmlString);
This will output the same XML string as above.
You can also use JSON.stringify
and replace
method to achieve this:
const arr = ['item1', 'item2', 'item3'];
const xml = '<?xml version="1.0" encoding="UTF-8"?>\n';
xml += '<root>\n';
xml += JSON.stringify(arr).replace(/"/g, '').replace(/\[/g, '').replace(/\]/g, '').replace(/,/g, '\n <item>');
xml += '</root>\n';
console.log(xml);
This will also output the same XML string as above.