title: Generate XML document in-memory with JavaScript
body: <p>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 routines, instead of appending countless strings together. I'm hoping jQuery can help me out.</p>
  
  <p>Let's say I need to generate this (toy) XML document with JavaScript:</p>
  
  <pre><code>&lt;report&gt;
      &lt;submitter&gt;
          &lt;name&gt;John Doe&lt;/name&gt;
      &lt;/submitter&gt;
      &lt;students&gt;
          &lt;student&gt;
              &lt;name&gt;Alice&lt;/name&gt;
              &lt;grade&gt;80&lt;/grade&gt;
          &lt;/student&gt;
          &lt;student&gt;
              &lt;name&gt;Bob&lt;/name&gt;
              &lt;grade&gt;90&lt;/grade&gt;
          &lt;/student&gt;
      &lt;/students&gt;
  &lt;/report&gt;
  </code></pre>
  
  <p>To start, I need to create some kind of an XML document object with the "report" root. I'm assuming one of these should be close, but none of them work quite right, and/or I can't quite figure out how to use the object properly:</p>
  
  <pre><code>function generateDocument1()
  {
      var report = $('&lt;report&gt;&lt;/report&gt;');
      return report;
  }
  
  function generateDocument2()
  {
      var report = document.implementation.createDocument(null, "report", null);
  
      return new XMLSerializer().serializeToString(report);   
  }
  
  function createXmlDocument(string)
  {
      var doc;
      if (window.DOMParser)
      {
          parser = new DOMParser();
          doc = parser.parseFromString(string, "application/xml");
      }
      else // Internet Explorer
      {
          doc = new ActiveXObject("Microsoft.XMLDOM");
          doc.async = "false";
          doc.loadXML(string); 
      }
      return doc;
  }
  
  function generateDocument3()
  {
      var report = createXmlDocument('&lt;report&gt;&lt;/report&gt;');
  
      return report;
  }
  </code></pre>
  
  <p>Now I want to create and append elements. How do I do that? I imagine it's something like this:</p>
  
  <pre><code>function generateReportXml()
  {
      // Somehow generate the XML document object with root
      var report = /*???*/;
  
      // Somehow create the XML nodes
      var submitter = /*???*/;
      var name = /*???*/;
  
      // Somehow append name to submitter, and submitter to report
      submitter.append(name); /*???*/
      report.append(submitter); /*???*/
  
      // ... append the rest of the XML
  
      return report;
  }
  </code></pre>
  
  <p>Any ideas?</p>