ilovett

MSXML Nodes and the power of SelectionLanguage

March 8th, 2005

Maybe you find yourself doing a little (or a lot) of Javascripting that involves XML. Requesting it remotely with the trendy xmlhttprequest object; doing client-side transformations; fancy-pants stuff like that. And maybe you've found yourself in the frustrating predicament of having your good old faithful getElementsByTagName() seem to break on you in Internet Explorer. I was, and here's what I found out.

On the mozilla side of the fence, if you have an xml document node stored in memory as xmlDoc and you want to get an array of all instances of a certain element, getElementsByTagName is the logical choice. That's what you'd do if you were manipulating an HTML document's DOM, so why should it be any different for XML held in memory?

But it is. This little gem from Microsoft gives a clue why. In point:

XML Path Language (XPath) queries can be used to query the XML documents with DOM methods such as selectNodes or selectSingleNode. The default query that is used is XSLPattern for backward compatibility. To use XPath, change the SelectionLanguage internal property of DOMDocument to XPath.

Don't ask me why, but in the IE and MSXML world, "XSLPattern for backward compatibility" somehow translates into "getElementsByTagName no worky".

Don't get mad, get even. Add the following after your IE branch creates an instance of MSXML:

xmlObj.setProperty("SelectionLanguage", "XPath");

Then gaze in wonder as getElementsByTagName springs back to life and order is restored to the universe!