Last active
December 14, 2015 14:59
-
-
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.
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
| // 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