Generate XML document in-memory with JavaScript

前端 未结 5 564
谎友^
谎友^ 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:38

    The second approach seems a good way to go. It was designed to work with XML documents. Once you have the document object created, use the standard XML DOM manipulation methods to construct the entire document.

    // creates a Document object with root ""
    var doc = document.implementation.createDocument(null, "report", null);
    
    // create the , , and text node
    var submitterElement = doc.createElement("submitter");
    var nameElement = doc.createElement("name");
    var name = doc.createTextNode("John Doe");
    
    // append nodes to parents
    nameElement.appendChild(name);
    submitterElement.appendChild(nameElement);
    
    // append to document
    doc.documentElement.appendChild(submitterElement);
    

    This may seem a little verbose but is the right way to build the XML document. jQuery does not actually construct any XML document, but just relies on the innerHTML property to parse and reconstruct a DOM given an HTML string. The problem with that approach is that when tag names in your XML collide with tag names in HTML such as

    or , then the results can be unpredictable. (EDIT: since 1.5 there's jQuery.parseXML() which does actually construct an XML document and thus avoids these problems — for parsing only.)

    To cut down on the verboseness, write a small helper library, or maybe a jQuery plugin to construct the document.

    Here's a quick and dirty solution to creating a XML document using a recursive approach.

    // use this document for creating XML
    var doc = document.implementation.createDocument(null, null, null);
    
    // function that creates the XML structure
    function Σ() {
        var node = doc.createElement(arguments[0]), text, child;
    
        for(var i = 1; i < arguments.length; i++) {
            child = arguments[i];
            if(typeof child == 'string') {
                child = doc.createTextNode(child);
            }
            node.appendChild(child);
        }
    
        return node;
    };
    
    // create the XML structure recursively
    Σ('report',
        Σ('submitter',
            Σ('name', 'John Doe')
        ),
        Σ('students',
            Σ('student',
                Σ('name', 'Alice'),
                Σ('grade', '80')
            ),
            Σ('student',
                Σ('name', 'Bob'),
                Σ('grade', '90')
            )
        )
    );
    

    Returns:

    ​John Doe​​Alice​​80​​Bob​​90​

    See example

    提交回复
    热议问题