Object/Array to XML converter
The following solution can turn a JS variable to a (non indented) XML string. It supports both lists (arrays) and objects.
- Use
objectToXml(object)
to create a valid XML with a single root element. - Use
variableToXml(variable, 'listElementName')
if you want to convert an array of elements. In this case, you have to pass the tag name for the list elements as the second argument.
function objectToXml(object) { if (object instanceof Array || Object.keys(object).length !== 1) { throw 'variable has to be an object with a single property' } return variableToXml(object)}function variableToXml(variable, arrayItemPropertyName = null) { if (Array.isArray(variable)) { return variable.reduce((xml, propertyValue) => { const value = variableToXml(propertyValue) return `${xml}<${arrayItemPropertyName}>${value}</${arrayItemPropertyName}>` }, '') } if (variable instanceof Object) { return Object.entries(variable).reduce((xml, [propertyName, propertyValue]) => { const value = variableToXml(propertyValue, propertyName ) const tag = propertyValue instanceof Array ? value : `<${propertyName}>${value}</${propertyName}>` return `${xml}${tag}` }, '') } return variable}
Input variable
const object = { rootTag: { intProperty: 4, stringProperty: 'foo', listOfElements: { element: [{ intProperty: 5, stringProperty: 'bar', }, { intProperty: 5, stringProperty: 'bar', }], }, list: { listElement: [1, 2, 3], }, },}
Output XML (prettified)
<rootTag><intProperty>4</intProperty><stringProperty>foo</stringProperty><listOfElements><element><intProperty>5</intProperty><stringProperty>bar</stringProperty></element><element><intProperty>5</intProperty><stringProperty>bar</stringProperty></element></listOfElements><list><listElement>1</listElement><listElement>2</listElement><listElement>3</listElement></list></rootTag>
Demo
const object = { rootTag: { intProperty: 4, stringProperty: 'foo', listOfElements: { element: [{ intProperty: 5, stringProperty: 'bar', }, { intProperty: 5, stringProperty: 'bar', }], }, list: { listElement: [1, 2, 3], }, },}console.log(objectToXml(object))function objectToXml(object) { if (object instanceof Array || Object.keys(object).length !== 1) { throw 'variable has to be an object with a single property' } return variableToXml(object)}function variableToXml(variable, arrayItemPropertyName = null) { if (Array.isArray(variable)) { return variable.reduce((xml, propertyValue) => { const value = variableToXml(propertyValue) return `${xml}<${arrayItemPropertyName}>${value}</${arrayItemPropertyName}>` }, '') } if (variable instanceof Object) { return Object.entries(variable).reduce((xml, [propertyName, propertyValue]) => { const value = variableToXml(propertyValue, propertyName ) const tag = propertyValue instanceof Array ? value : `<${propertyName}>${value}</${propertyName}>` return `${xml}${tag}` }, '') } return variable}