@scalar/oas-utils
Version:
Open API spec and Yaml handling utilities
53 lines (51 loc) • 1.81 kB
JavaScript
/**
* This function converts an object to XML.
*/
function json2xml(data, tab) {
const toXml = (value, key, indentation) => {
let xml = '';
if (Array.isArray(value)) {
for (let i = 0, n = value.length; i < n; i++) {
xml += indentation + toXml(value[i], key, indentation + '\t') + '\n';
}
}
else if (typeof value === 'object') {
let hasChild = false;
xml += indentation + '<' + key;
for (const m in value) {
if (m.charAt(0) === '@') {
xml += ' ' + m.substr(1) + '="' + value[m].toString() + '"';
}
else {
hasChild = true;
}
}
xml += hasChild ? '>' : '/>';
if (hasChild) {
for (const m in value) {
if (m === '#text') {
xml += value[m];
}
else if (m === '#cdata') {
xml += '<![CDATA[' + value[m] + ']]>';
}
else if (m.charAt(0) !== '@') {
xml += toXml(value[m], m, indentation + '\t');
}
}
xml += (xml.charAt(xml.length - 1) === '\n' ? indentation : '') + '</' + key + '>';
}
}
else {
xml += indentation + '<' + key + '>' + value.toString() + '</' + key + '>';
}
return xml;
};
let xml = '';
// biome-ignore lint/nursery/useGuardForIn: Yeah, it’s ok. But feel free to fix it.
for (const key in data) {
xml += toXml(data[key], key, '');
}
return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, '');
}
export { json2xml };