Chapter 8 Working with XML Documents
You can access the attributes of an element in the following ways:
attributes
property.getAttribute
or getAttributeNode
methods
of the DOMElement
object.
The following example writes out the names and values of the attributes of an element.
function displayAttributes( node ){ //1
var i; //2
var attnode; //3
if( node.nodeType == 1){ //4
for( j=0; j < node.attributes.length; j++){ //5
attnode = node.attributes.item(j) //6
document.writeln( attnode.nodeName ); //7
document.writeln( attnode.firstChild.nodeValue );
}
}
}
If the supplied element has a start tag of this form:
<Region Type="Province">
Then the output is:
Type
Province
In this example, the attribute node has a child
that is a text object. The nodeValue
of
this text object can also be used to retrieve the attribute value.
DOMNode
object that
represents an attribute has no parents and no siblings. Any attempt
to access these properties returns null.
attributes
property
of the element node. This property returns a DOMNamedNodeMap
object.
You can access the individual attributes either by index (as in
the sample code above) or by name. The following statement sets attnode
to
the Type attribute of the element:
attnode = node.attributes.getNamedItem( "Type" );
The DOMAttribute
object
corresponds to an attribute of an XML element. The DOMAttribute
object
inherits all the properties and methods from the DOMNode
object.
In addition, it supports some properties and methods specific to
attributes.
You can access the attributes of an element in the following ways:
elemList
),
and lists the value of all the Type attributes:for( i = 0 ; i < elemList.length ; i ++ ){
elem = elemList.item(i);
document.writeln( elem.getAttribute( "Type" ) );
}
for( i = 0 ; i < elemList.length ; i ++ ){
elem = elemList.item(i);
att = elem.getAttributeNode( "Type" );
document.writeln( att.name + " = " + att.value );
}
The DOMAttribute object also has methods and properties that you can use to alter XML documents. For more information, see "Using the DOM interface to create and edit XML documents".
Copyright © 1999 Sybase, Inc. All rights reserved. |