March 14, 2002 - Using Attribute Values to Search for DOMDocument Nodes
March 14, 2002 Using Attribute Values to Search for DOMDocument Nodes Tips: March 2002
Yehuda Shiran, Ph.D.
|
@
character. To match all week
nodes where the attribute dvds_rented
is 12000
, you will write this (try it):
var matchedNodes = xmlDoc.selectNodes('//week[@dvds_rented = "12000"]');
alert("Number of matched nodes: " + matchedNodes.length);
Notice we found one week
node that answers this query, as expected. Also notice the two forward slashes. They are needed because the week
nodes are not directly beneath the context node (root), but rather deep in the tree. We can change the context to January
and then can start the search at the week
's father (try it):
var matchedNodes = xmlDoc.childNodes[3].childNodes[1].childNodes[0].
selectNodes('week[@dvds_rented = "12000"]');
alert("Number of matched nodes: " + matchedNodes.length);
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 <&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>