Skip to content

Instantly share code, notes, and snippets.

@djsipe
Last active October 27, 2017 16:43
Show Gist options
  • Save djsipe/67a7653ad5d33e9bb3b2c133073b750a to your computer and use it in GitHub Desktop.
Save djsipe/67a7653ad5d33e9bb3b2c133073b750a to your computer and use it in GitHub Desktop.
Serialize a `Document` to a XML string.
/**
* Serialize a document to a string the hard way (using lodash)
* @param {Document} xml
* @return {String}
*/
function documentToXmlString(xml) {
var xmlString = "";
function serialize(xmlDoc) {
_.forEach(xmlDoc.childNodes, function (el) {
if (el.nodeType == Node.TEXT_NODE) {
xmlString += _.escape(el.textContent);
return;
}
xmlString += "<" + el.nodeName; // Open tag
// Loop over the attributes and append them
_.forEach(el.attributes, function(attribute) {
xmlString += " " + attribute.name + '="' + _.escape(attribute.value) + '"';
});
if (el.hasChildNodes()) {
// If there are child nodes, loop over them recursively
xmlString += ">";
serialize(el);
xmlString += "</" + el.nodeName + ">";
}
else {
// No child nodes, use a self-closing tag
xmlString += '/>';
}
});
}
return serialize(xml);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment