I wrote the following function to make this work. Works very well when collections (arrays) inside your object have the suffix "s" (as the plural for their contents).
function serializeNestedNodeXML(xmlDoc, parentNode, newNodeName, obj) { if (Array.isArray(obj)) { var xmlArrayNode = xmlDoc.createElement(newNodeName); parentNode.appendChild(xmlArrayNode); obj.forEach(function (e) { serializeNestedNodeXML(xmlDoc, xmlArrayNode, newNodeName.substring(0, newNodeName.length - 1), e) }); return;
And I called it this way (as a function of the serialized class itself):
this.serializeToXML = function () { var xmlDoc = document.implementation.createDocument(null, "YourXMLRootNodeName", null); serializeNestedNodeXML(xmlDoc, xmlDoc.documentElement, 'YourSerializedClassName', this); var serializer = new XMLSerializer(); return serializer.serializeToString(xmlDoc); }
But after an hour, I switched to JSON ...
Martin
source share