Skip to content

Instantly share code, notes, and snippets.

@whump
Last active December 14, 2015 14:59
Show Gist options
  • Select an option

  • Save whump/5104717 to your computer and use it in GitHub Desktop.

Select an option

Save whump/5104717 to your computer and use it in GitHub Desktop.
You need to return XML to an API. Unfortunately IE8 and older is still inconsistent with how modern browsers handle XML document creation. You still don't want to create XML by concatenating strings, but you have jQuery.
// Assuming that you have JQuery and Underscore in your global namespace
// you have an array of strings you want to convert to an XML document
function toXML(data) { // data = ['string'(, ...)]
var s = '', $xml;
// build an empty structure
// <items><item/><item/>...</items>
// yes, this is string concatenation,
// but we control the vocabulary
_(this.length).times(function() { s = s + '<item/>'; });
s = '<items>' + s + '</items>';
// parse it into an XML document
xml = $.parseXML(s);
$xml = $(xml); // wrap the document so we can use JQuery methods
// now add a text node to each of the 'item' children
// because attempting to append nodes to $xml fails in IE8
$xml.find('item').text(function(i, old) {
return data[i];
});
// now call the appropriate serializer
// FIXME: find the IE9+ serializer
if (window.ActiveXObject) {
s = xml.xml;
}
else {
s = new XMLSerializer().serializeToString(xml);
}
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment