Generate XML document in-memory with JavaScript

前端 未结 5 548
谎友^
谎友^ 2020-11-27 13:15

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

5条回答
  •  一向
    一向 (楼主)
    2020-11-27 13:40

    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: "12"
    */
    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}`;
    }
    
    // Example:
    const report = {
        submitter: { name: "John Doe" },
        students: {
            student: [{ name: "Alice", grade: 80 }, 
                      { name: "Bob",   grade: 90 }]
        }
    };
    
    console.log(
        '' +
        toXml("report", report));

提交回复
热议问题