February 28, 2002 - Using A Collection of Selected Nodes | WebReference

February 28, 2002 - Using A Collection of Selected Nodes

Yehuda Shiran February 28, 2002
Using A Collection of Selected Nodes
Tips: February 2002

Yehuda Shiran, Ph.D.
Doc JavaScript

All DOMDocument 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.

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

  matchedNodes = xmlDoc.childNodes[3].childNodes[1].childNodes[0].
    selectNodes('./week');
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].

Here is mydvd7.xml for your reference:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="mydvd7.xsl"?>
<!DOCTYPE sales SYSTEM "mydvd7.dtd">
  <sales>
    <summary>
      <heading>MyDVD Rental Store</heading>
      <subhead>Periodical Sales Report</subhead>
      <description>Sales Report for January, February, 
	    and &lt;&month;&gt; of 2001</description>
	  <author>author: &preparedby;</author>
	  <date>Jan 30, 2002</date>
    </summary>
	<data>
      <month>
        <name>January 2001</name>
        <week number="1" dvds_rented="12000" />
        <week number="2" dvds_rented="15000" />
        <week number="3" dvds_rented="18000" />
        <week number="4" dvds_rented="11800" />		  
      </month>
      <month>
        <name>February 2001</name>
        <week number="1" dvds_rented="11500" />
        <week number="2" dvds_rented="12390" />
        <week number="3" dvds_rented="19050" />
        <week number="4" dvds_rented="11200" />		  
      </month>
      <month>
        <name>March 2001</name>
        <week number="1" dvds_rented="15300" />
        <week number="2" dvds_rented="12390" />
        <week number="3" dvds_rented="10050" />
        <week number="4" dvds_rented="11230" />		  
      </month>
    </data>
  </sales>