XML Objectified: Attributes Considered
December 21, 1998
Looking back at the pets.xml file you'll notice that
the <pet> tag contains an attribute,
named name. This provides us with a smooth
segue into looking at attributes of an XML element. You
already know how to access the node which represents an XML
element, but let's say you would like to zoom in on
an attribute of an element. Attributes are considered
something of a "special case" in the XML DOM because
they do not cleanly fit into the parent-child or branch-leaf
metaphors. For elements which possess attributes the
IDOMElement object contains an attributes list, which is an
IDOMNamedNodemap of
IDOMAttribute
objects, with which you can inspect attributes and their
values associated with a particular element.
The following chart of properties and methods illustrates
how to access various facets of the attributes
list. We're again relying on the ongoing example -- follow
along with the pets.xml document and this will make
sense.
|
petbase.childNodes(1).childNodes(0).attributes.length |
yields
|
1 |
|
petbase.childNodes(1).childNodes(0).attributes(0).nodeName |
yields |
"name" |
|
petbase.childNodes(1).childNodes(0).attributes.getNamedItem("name") |
yields |
"ella dibella" |
|
petbase.childNodes(1).childNodes(0).attributes.item(0) |
yields |
"ella dibella" |
The last two examples in the above table both yield
the same result because they both return the value of the
same attribute. Note, however, that the getNamedItem()
method is preferable, because it guarantees which
attribute's value will be returned. There is no guarantee
in the XML DOM that all attributes of an element will
always be stored in the same index order so you cannot
be sure that attribute 0, for instance, will always reflect
the name attribute in this case.
XML Objectified: IDOMElement
XML via the Document Object Model: A Preliminary Course
XML Objectified: IDOMElement's Revisited
|