Thursday, August 23, 2007

Using Javascript to parse XML text

As I was and still am heavily involved in my company’s next major product release, I a kinda slacked off on writing valuable things down when I encounter them.

To make it up, here is something that I was trying to do yesterday.

I need to parse a complex data structure in JSON, and inside the JSON, I would have to deal with some values that are xml, So xml within JSON ;-)

First thing I thought is to create a node using document.createElement, and set the innerHTML of the element to be the value of the JSON xml, then I should be able to access the nodes inside the element that I created just like normal node traversing. (parentNode, childNodes, firstChild, etc…).

It worked with Firefox ;-), but not IE.

I remembered that the library sarissa can do the xslt transformation, so I should be able to find the code in there which handles the string to traversable xml tree conversion.

Guess what, I didn’t have enough time to look through all of the docs to see exactly how it was done, and something else hit me when I was searching through the web.

I was so glad that I don’t have to copy over the 23k lib just to turn the text into xml in IE after reading XML Parser.

So here is the code snippets:
    if (window.ActiveXObject) { // ie
xml=new ActiveXObject("Microsoft.XMLDOM");
} else { // mozilla
var parser=new DOMParser();

No comments: