Browser-independent XPath with Javascript

Now that you're able to load XML and transform it using an XSL stylesheet, wouldn't it be handy to also be able to perform XPath selects/functions on that XML outside of the stylesheet's formatting? Why, yes. Yes, it would:

Javascript code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function xpSelect(xmlDoc, xpathStr)  
{  
    try {  
        if(xmlDoc.evaluate) {  
            // WebKit (Safari, Chrome), Mozilla/Firefox, Opera, etc.  
            var xpr = xmlDoc.evaluate(xpathStr, xmlDoc, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);  
            var cur = xpr.iterateNext();  
            var a = 0;  
            var retarr = [];

            // build array from returned nodes  
            while(cur) {  
                retarr[a++] = cur;  
                cur = xpr.iterateNext();  
            }

            return(retarr);  
        } else {  
            // Internet Explorer  
            return(xmlDoc.selectNodes(xpathStr));  
        }  
    } catch(e) {  
        alert("Error:\n" + e.message);  
        return false;  
    }  
}

It's worth noting that IE's selectNodes() method is drastically slower than the standard evaluate() method, but this function's results will be the same: an array of element objects. The function is rather base in its implementation, but could be modified to return custom data sets (or a DOM tree/node) instead of an array. Either way, //state[@name='Alabama']/areacode is just a function call away!

Comments !