Chapter 8 Working with XML Documents
Many applications that process XML documents need to locate or manipulate various elements of the document by using the tree structure.
The DOM interface provides two ways of working with elements:
DOMNode
object
and test to see if the node you are addressing is an element node.DOMElement
object, which
provides some additional properties and methods that reflect the features
of XML elements.
The element nodes of a document have all the properties (parents, siblings, children) that you need to navigate a document. These nodes provide one way of accessing the properties of elements.
Here is a script that writes out the names of all elements in a document:
function displayElementName( domElement ){ //1
var i; //2
var domChild; //3
if( domElement.nodeType == 1){ //4
document.writeln( domElement.nodeName ); //5
} //6
for( i=0; i < domElement.childNodes.length ; i++ ){//7
domChild = domElement.childNodes.item(i); //8
displayElementName( domChild ); //9
} //10
} //11
displayElementName( domDoc.documentElement ); //12
displayElementName
on
each.displayElementName
with
the document element of a DOM document. The function must be defined
before it is used.
Nodes that correspond to elements have the following characteristics:
nodeType
of
a node that is an element is 1.nodeValue
of
a node that is an element is null.DOMNamedNodeMap
object.The DOMElement
object
corresponds to an element of an XML document. DOMElement
inherits
all the properties and methods from the DOMNode
object. In
addition, it supports some properties and methods specific to elements.
You can retrieve and process all elements with a given name from a document as follows:
elemlist = domObj.getElementsByTagName(tag_name);
for(i=0; i < elemlist.length ; i++){
document.writeln( elemlist.item(i).tagName);
}
where domObj
is
a DOMDocument
object or
a DOMElement
object, and tag_name is
the case-sensitive name of the tag you want to retrieve. If domObj is
a DOMElement
object, only
those elements contained in domObj are retrieved (descendants of
domObj).
This is usually more effective than traversing the entire document tree looking for a particular element.
For a list of DOMElement
properties
and methods, see "The DOMElement object" in PowerDynamo
Reference.
Copyright © 1999 Sybase, Inc. All rights reserved. |