I am working on a Web application that needs to send XML to a server backend. I\'d like to build a XML document in-memory on the client-side, but using XML manipulation rout
If your desired XML structure can be represented in a JavaScript object having the same structure, then you could create such an object and use the following function to convert that object to XML:
/* Arguments:
name: name of the root XML-element
val: the data to convert to XML
Returns: XML string
Example: toXml("root", { items: { item: [1, 2] } })
returns: "- 1
- 2
"
*/
function toXml(name, val) {
const map = {"<":"<", ">":">", "&":"&", "'":"&apos", '"':"""};
if (Array.isArray(val)) return val.map(elem => toXml(name, elem)).join``;
const content = Object(val) === val
? Object.keys(val).map(key => toXml(key, val[key])).join``
: String(val).replace(/[<>&'"]/g, m => map[m]);
return `<${name}>${content}${name}>`;
}
// Example:
const report = {
submitter: { name: "John Doe" },
students: {
student: [{ name: "Alice", grade: 80 },
{ name: "Bob", grade: 90 }]
}
};
console.log(
'' +
toXml("report", report));