Although the childNodes example on the previous page demonstrated how to traverse the children of a node, no practical information was returned. What would be far more useful in the case of our cd collection would be to return the id of each cd.
<cd id="0001">
This key / value pair is called an Attribute.
In DOMIT!, attributes are a member of the class DOMIT_Attr. A DOMIT_Element can contain any number of attributes. These are placed in a collection of nodes called a NamedNodeMap.
Warning! Prior to DOMIT! 0.7, attributes were stored in a PHP associative array. Array-based access to attributes will no longer work unless you are using DOMIT_Lite!
A number of methods for the manipulation of attributes are available. These include:
getAttribute($name), which allows you to retrieve the value of the named attribute.
setAttribute($name, $value), which allows you to set the value of the named attribute.
removeAttribute($name), which removes the named attribute.
hasAttribute($name), which determines whether the named attribute exists.
getAttributeNode($name), which allows you to retrieve the attribute node with a key of $name.
setAttributeNode($name, $value), which allows you to set the value of the named attribute node.
removeAttributeNode($name), which removes the named attribute.
We will therefore modify our childNodes loop from the previous page so that it echoes the id number of each cd rather than its tag name.
if ($cdCollection->documentElement->hasChildNodes()) {
$myChildNodes =& $cdCollection->documentElement->childNodes;
$numChildren =& $cdCollection->documentElement->childCount;
for ($i = 0; $i < $numChildren; $i++) {
echo ("The id of child node $i is: " .
$myChildNodes[$i]->getAttribute("id") .
"<br />");
}
}
The above example will return:
The id of child node 0 is: 0001
The id of child node 1 is: 0002
The id of child node 2 is: 0003
NOTE: The methods getAttributeNode,
setAttributeNode, and removeAttributeNode
are not available in DOMIT! Lite, because attributes are not full-fledged nodes, but items in an associative array.
|