Chapter 8 Working with XML Documents


Using the DOM interface to create and edit XML documents

You can output XML data from a database using standard string functions. The DOM interface lets you construct or modify the DOM representation of an XML document. To do anything with this document, you must process it using the DOM interfaces described in the other sections of this chapter.

Creating a DOM document object

The DOMDocument object has a constructor that allows you to create an empty DOM document. Use the following statement:

domDoc = new DOMDocument();

The DOM Level 1 specification does not provide a standard method for creating a DOM document object. The DOMDocument() constructor is an extension to the standard.

Adding objects to DOM documents

Create the element or other object you want to add, and then insert it in the proper place in the tree.

Creating objects

To create an element or other object, use these methods of the DOMDocument object:

The following fragment creates an FName element (elem ), and a text node (tnode ) with content "Ann T. Dote" in a DOMDocument object named domDoc:

elem = domDoc.createElement( "FName" );
tnode = domDoc.createTextNode( "Ann T. Dote" );

These nodes currently have no place in the document, and the FName element has no content.

Adding objects to documents

To add objects to a node, use one of these methods of the DOMNode object:

This fragment expands on the previous one to add the elements into a document. The FName element is a child of a node named cust , and the text node is a child of the FName element:

elem = domDoc.createElement( "FName" );
text = domDoc.createTextNode("Ann T. Dote" );
el = cust.appendChild( elem );
el.appendChild( text );

For more information, see "insertBefore method" and "replaceChild method" in the PowerDynamo Reference Manual.

Removing and replacing objects in DOM documents

The DOM interface provides a set of methods for deleting and replacing objects in the document tree. There is not a method on a DOMNode object to delete the object itself. Instead, you delete a node by using the appropriate method on its parent. The removeChild method deletes a child node, and the replaceChild method replaces a child node with a new node.

For more information, see "removeChild method" and "replaceChild method" in the PowerDynamo Reference Manual.

Removing and replacing attributes

For attributes and other unordered objects (not elements), you can also use methods defined on the collection of attributes. This collection, which is unordered, is represented by a DOMNamedNodeList object, and you can use the removeNamedItem method and the setNamedItem method to carry out the operations.

For more information, see "removeNamedItem method" and "setNamedItem method" in the PowerDynamo Reference Manual.

 


Copyright © 2001 Sybase, Inc. All rights reserved.