February 26, 2002 - Selecting Nodes with XSL Patterns
February 26, 2002 Selecting Nodes with XSL Patterns Tips: February 2002
Yehuda Shiran, Ph.D.
|
DOMDocument
tree for a particular node may be quite complex. To simplify this task, you can use patterns to select a group of nodes that match your selection criteria. These patterns are called XSL patterns. The following function matches the hierarchical nodes "/sales/data/month/week"
. If you look at our mydvd7.xml
file (see below), you'll see that there are 12 such nodes:
function applyXSL() {
var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
xmlDoc.async = false;
xmlDoc.load("mydvd7.xml");
var matchedNodes = xmlDoc.selectNodes('/sales/data/month/week');
alert("Number of matched nodes: " +
matchedNodes.length);
alert("The second attribute name of the seventh matched node: " +
matchedNodes[6].attributes[1].nodeName);
alert("The second attribute value of the seventh matched node: " +
matchedNodes[6].attributes[1].text);
}
Try it. You can see that indeed there are 12 nodes that match the filtering criteria. Also notice the seventh (out of 12) node's attribute name and value that we add here for better clarity.Here is the XML file:
<?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 <&month;> 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>