Internet Explorer DOMDocument & XPath

I discovered a couple of interesting things about Internet Explorer’s MSXML2.DOMDocument object. It turns out that there are essentially two “production-quality” versions of it available: 3.0 and 6.0. Version 6.0 is much the better version, but it’s quite new, and not available on all systems. This means that in IE7 and IE8, instantiating a new MSXML2.DOMDocument object gives you version 3.0.

Now most of the time, this isn’t a problem. Today, though, I was constructing an XPath expression that used the substring() function; something like this:

//Element[substring(Child, 1, 3)='abc']

This will pull all Elements with a Child element whose value’s first three characters are “abc”. Not particularly complex. It turns out, though, that version 3.0 or the DOMDocument doesn’t actually use XPath as its default language: it uses a bastardised version of XPath called “XSLPatterns”, which just so happens to not support the substring() function at all.

So how do we deal with this situation? One way is to always instantiate version 6.0 of the DOMDocument:

xd = new ActiveXObject('msxml2.DOMDocument.6.0')

The problem with this approach is that, like I mentioned earlier, you can’t always be guaranteed that your users will have version 6.0 installed (even though it’s a free download). The safer way to deal with this problem is to switch the expression language to XPath in your 3.0 object:

xd = new ActiveXObject('msxml2.DOMDocument');
xd.setProperty("SelectionLanguage", "XPath");

The advantage of this approach is that you’re not specifying a version, so when MS eventually changes the default to 7.0 (or whatever), your code will work without a problem.

For more information on this, check out  this blog post from Microsoft’s XML team, which goes into a little bit more detail.