Web Services, Part IX: Pattern-Based XML Node Selection: Node Selection - Doc JavaScript | WebReference

Web Services, Part IX: Pattern-Based XML Node Selection: Node Selection - Doc JavaScript

Web Services, Part IX: Pattern-Based XML Node Selection

Node Selection

Pattern-based selection can be based on two standards: XSLT, and XPath. Let's start with the more extensive one, XPath. Since the default is XSLT patterns, you need to change the SelectionLanguage property to XPath. Start off your page with the following lines to read mydvd7.xml:

  var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
  xmlDoc.async = false;
  xmlDoc.setProperty("SelectionLanguage", "XPath");

All DOMDocument's selection operations are done through two methods, selectNodes() and selectSingleNode(). When calling these methods, the owner instance node object determines the context of the pattern-based selection. The selectNodes() method returns all nodes matching the given pattern. The selectSingleNode() returns the first of these nodes.

Let's look at an example. The following selection (try it) returns the four weeks of January:

matchedNodes = xmlDoc.childNodes[3].childNodes[1].

The selectNodes() method returns a collection of nodes. In the alert box above we output the number of elements in this collection by:

alert("Number of matched nodes: " + matchedNodes.length);

You can access this collection in many different ways. You can reference each one of the elements as an array element. The four week node objects are matchedNodes[0], matchedNodes[1], matchedNodes[2], and matchedNodes[3].

The selectSingleNode() method returns the first match. Using the same pattern as above, we should get the first week of January by the following two lines (try it):

var selectedNodes = xmlDoc.childNodes[3].childNodes[1].
alert("Name of selected node: " + selectedNodes.nodeName);

The XPath standard is based on Unix notation. The single period (.) designates the current node. The forward slash (/) delimits between a father and his son. Using examples, we'll use the rest of this column to explain the patterns supported by the XPath standard.

Next: How to specify patterns - Part A


Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: February 25, 2002
Revised: February 25, 2002

URL: http://www.webreference.com/js/column104/4.html