对象/数组转XML转换器
以下解决方案可以将JS变量转换为(非缩进)XML字符串。它支持列表(数组)和对象。
- 使用
objectToXml(object)
创建一个带有单个根元素的有效XML。
- 如果要转换元素数组,请使用
variableToXml(variable, 'listElementName')
。在这种情况下,您必须将列表元素的标记名称作为第二个参数传递。
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
}
输入变量
const object = {
rootTag: {
intProperty: 4,
stringProperty: 'foo',
listOfElements: {
element: [{
intProperty: 5,
stringProperty: 'bar',
}, {
intProperty: 5,
stringProperty: 'bar',
}],
},
list: {
listElement: [1, 2, 3],
},
},
}
输出格式化的 XML
<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>
演示
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
}