Friday, April 06, 2012

Cross browser selectSingleNode for XML in Javascript

Internet Explorer has a non-standard method available in XML documents returned from AJAX calls called selectSingleNode. Pass in some XPath and it returns the first node that matches the XPath. Other browsers have ways of doing the same thing, but they are more long winded. So in short, I like the IE implementation and since I don’t fiddle with XML in JavaScript that often I often forget that selectSingleNode is not supported on all browsers (and if you’re wondering why I use IE as my primary browser, it’s because it’s still, just about, the most popular browser out there).

So here’s a cross browser version of selectSingleNode (not my own work, copy and pasted from somewhere I can’t remember on the web)

    function SelectSingleNode(xmlDoc, elementPath) {
      if (xmlDoc.evaluate) {
        var nodes = xmlDoc.evaluate(elementPath, xmlDoc, null, XPathResult.ANY_TYPE, null);
        var results = nodes.iterateNext();
        return results;
      }
      else
        return xmlDoc.selectSingleNode(elementPath); 
    }

Update – This no longer works in IE10, since selectSingleNode has been removed from the XML document returned from AJAX calls. This can be worked around by setting the response type of the XmlHttpRequest, like so

xhr.responseType =  'msxml-document';

More info

Update – There’s a more fully featured version of this now available

5 comments:

MikeAinOz said...

Thank Doogal , I'll give it a go. This came up on the first page of my goggle search!

Anonymous said...

Can u post me with an example?

Mark Hetherington said...

Bummer - this doesn't work in IE10 anymore as they've removed selectSingleNode.

Chris Bell said...

That's bizarre! They removed selectSingleNode but didn'r add support for document.evaluate. So there's no obvious way to get it working in IE10, other than changing AJAX calls to return MS XML documents.
More info

Steven said...

Many Thanks your

objXHR.responseType = 'msxml-document';

Totally fixed my issue!