04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 15: XML in JavaScript<br />

(continued)<br />

var result = doc.evaluate(expression, context, nsresolver,<br />

XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);<br />

var nodes = new Array();<br />

if (result !== null){<br />

for (var i=0, len=result.snapshotLength; i < len; i++){<br />

nodes.push(result.snapshotItem(i));<br />

}<br />

}<br />

return nodes;<br />

} else if (typeof context.selectNodes != “undefined”){<br />

//create namespace string<br />

if (namespaces instanceof Object){<br />

var ns = “”;<br />

for (var prefix in namespaces){<br />

if (namespaces.hasOwnProperty(prefix)){<br />

ns += “xmlns:” + prefix + “=’” + namespaces[prefix] + “’ “;<br />

}<br />

}<br />

doc.setProperty(“SelectionNamespaces”, ns);<br />

}<br />

var result = context.selectNodes(expression);<br />

var nodes = new Array();<br />

for (var i=0,len=result.length; i < len; i++){<br />

nodes.push(result[i]);<br />

}<br />

}<br />

return nodes;<br />

} else {<br />

throw new Error(“No XPath engine found.”);<br />

}<br />

As you can see, much of the same logic is used from selectSingleNode() . In the DOM portion of the<br />

code, an ordered snapshot result type is used and then stored in an array. To match the IE implementation,<br />

the function should return an array even if no results were found, so the nodes array is always returned.<br />

In the IE branch of the code, the selectNodes() method is called and then the results are copied into an<br />

array. Since IE returns a NodeList , it ’ s best to copy the nodes over into an array, so the function returns<br />

the same type regardless of the browser being used. This function can then be used as follows:<br />

var result = selectNodes(xmldom.documentElement, “wrox:book/wrox:author”,<br />

{ wrox: “http://www.wrox.com/” });<br />

alert(result.length);<br />

For the best cross - browser compatibility, it ’ s best to use these two methods exclusively for XPath<br />

processing in JavaScript.<br />

538

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!