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.
Let's say I need to generate this (toy) XML document with JavaScript:
<report>
<submitter>
<name>John Doe</name>
</submitter>
<students>
<student>
<name>Alice</name>
<grade>80</grade>
</student>
<student>
<name>Bob</name>
<grade>90</grade>
</student>
</students>
</report>
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:
function generateDocument1()
{
var report = $('<report></report>');
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('<report></report>');
return report;
}
Now I want to create and append elements. How do I do that? I imagine it's something like this:
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;
}
Any ideas?