Chapter 8 Working with XML Documents


Working with elements

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:

Using the DOMNode object to work with 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.

Example

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

Notes

Characteristics of nodes that represent elements

Nodes that correspond to elements have the following characteristics:

Using the DOMElement object to work with elements

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.

Getting elements by tag name

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.