UNPKG

counterfact

Version:

a library for building a fake REST API for testing

55 lines (54 loc) 1.58 kB
function xmlEscape(xmlString) { return xmlString.replace(/["&'<>]/gu, (character) => { switch (character) { case "<": { return "&lt;"; } case ">": { return "&gt;"; } case "&": { return "&amp;"; } case "'": { return "&apos;"; } case '"': { return "&quot;"; } default: { return character; } } }); } function objectToXml(json, schema, name) { const xml = []; const attributes = []; Object.entries(json).forEach(([key, value]) => { const properties = schema?.properties?.[key]; if (properties?.attribute) { attributes.push(` ${key}="${xmlEscape(String(value))}"`); } else { xml.push(jsonToXml(value, properties, key)); } }); return `<${name}${attributes.join("")}>${String(xml.join(""))}</${name}>`; } export function jsonToXml(json, schema, keyName = "root") { const name = schema?.xml?.name ?? keyName; if (Array.isArray(json)) { const items = json .map((item) => jsonToXml(item, schema?.items, name)) .join(""); if (schema?.xml?.wrapped) { return `<${name}>${items}</${name}>`; } return items; } if (typeof json === "object" && json !== null) { return objectToXml(json, schema, name); } return `<${name}>${String(json)}</${name}>`; }