March 26, 2002 - Using "*[@]" to Match DOMDocument Nodes by Attribute Names
March 26, 2002 Using "*[@]" to Match DOMDocument Nodes by Attribute Names Tips: March 2002
Yehuda Shiran, Ph.D.
|
*[@dvds_rented]
matches all nodes having the attribute dvds_rented
in mydvd7.xml
. The context may change. The pattern /*[@dvds_rented]
will match nodes only at the root. The pattern //*[@dvds_rented]
will match nodes any level below the root (try it):
var matchedNodes = xmlDoc.selectNodes('//*[@dvds_rented]');
alert("Number of matched nodes: " + matchedNodes.length);
The pattern @dvds_rented
will match nodes at the current level. If the context is the first week of January, we should get a single week
node (try it):
var matchedNodes = xmlDoc.childNodes[3].childNodes[1].childNodes[0].
childNodes[1].selectNodes('@dvds_rented');
alert("Number of matched nodes: " + matchedNodes.length);
Similar patterns are also possible. The pattern week/@dvds_rented
will match 4 nodes when the context is the month of January (try it):
var matchedNodes = xmlDoc.childNodes[3].childNodes[1].childNodes[0].
selectNodes('week/@dvds_rented');
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>