Last active
October 27, 2017 16:43
-
-
Save djsipe/67a7653ad5d33e9bb3b2c133073b750a to your computer and use it in GitHub Desktop.
Serialize a `Document` to a XML string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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