javascript ant

RSS or Atom

 

Piles of javascript goodness
 

XHR responseXML to a String

 

You'll likely never have to do this, but recently I did. I had to take the responseXML property of the XHR object and turn it into a string. Now, you'd think this would be easy, but in fact you'd be wrong. Before I show how this is done, let's not forget that if you want an XML document as a string, you can simply use the responseText property instead of the responseXML property.

Doing this will provide you with a string version of the XML document. This avoids having to turn an XML object into a string in the browser. However, let's just say that you want the flexibility of both. That is, you want to have a an XML document as an XML object in JavaScript and at the same time have a string version of the XML document. Let's first start with an XML document. This will do.

To run this on your own server, save a version of the XML as test.xml and place it on your HTTP server. Next, we need a bit of code to do an XHR request and the magical code to transform an XML object to a string.

Take the HTML code above and save it on your server in the same directory as the test.xml file. To test this code, run the HTML file in a browser being served from your HTTP server (required for XHR). If everything runs correctly you should see the XML document in your web browser.

The magic sauce is found in the following line.

Here we are taking the XHR responseXML and turning it into a string for IE browsers using the .xml property of an XML object, and for all other browsers we are using (new XMLSerializer()).serializeToString(xhrRequest.responseXML).

So, like I said before, you'll likely never have to do this. But if you ever need to, you now know how.