//select single node
1 function selectsingleNode(context, expression, namespaces) { 2 var doc = (context.nodeType != 9 ? context.ownerDocument : context); 3 4 if (typeof doc.evaluate != "undefined") { 5 var nsresolver = null; 6 if (namespaces instanceof Object) { 7 nsresolver = function (prefix) { 8 return namespaces[prefix]; 9 }; 10 } 11 12 var result = doc.evaluate(expression, context, nsresolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null); 13 return (result !== null ? result.singleNodeValue : null); 14 } else if (typeof context.selectSingleNode != "undefined") { 15 16 //create namespace string 17 if (namespaces instanceof Object) { 18 var ns = ""; 19 for (var prefix in namespaces) { 20 if (namespaces.hasOwnProperty(prefix)) { 21 ns += 'xmlns:' + prefix + "='" + namespaces[prefix] + "'"; 22 } 23 } 24 doc.setProperty("SelectionNamespaces", ns); 25 } 26 return context.selectSingleNode(expression); 27 } else { 28 throw new Error("no xpath engine found"); 29 } 30 }
//select nodes
1 function selectNodes(context, expression, namespaces) { 2 var doc = (context.nodeType != 9 ? context.ownerDocument : context); 3 4 if (typeof doc.evaluate != "undefined") { 5 var nsresolver = null; 6 if (namespaces instanceof Object) { 7 nsresolver = function (prefix) { 8 return namespaces[prefix]; 9 }; 10 } 11 12 var result = doc.evaluate(expression, context, nsresolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); 13 var nodes = new Array(); 14 15 if (result != null) { 16 for (var i = 0, len = result.snapshotLength; i < len; i++) { 17 nodes.push(result.snapshotItem(i)); 18 } 19 } 20 21 return nodes; 22 } else if (typeof context.selectNodes != "undefined") { 23 24 //create namespace string 25 if (namespaces instanceof Object) { 26 var ns = ""; 27 for (var prefix in namespaces) { 28 if (namespaces.hasOwnProperty(prefix)) { 29 ns += "xmlns:" + prefix + "='" + namespaces[prefix] + "'"; 30 } 31 } 32 doc.setProperty("SelectionNamespaces", ns); 33 } 34 var result = context.selectNodes(expression); 35 var nodes = new Array(); 36 37 for (var i = 0, len = result.length; i < len; i++) { 38 nodes.push(result[i]); 39 } 40 41 return nodes; 42 } else { 43 throw new Error("no xpath engine found"); 44 } 45 }