Chapter 8 Working with XML Documents


Creating the DOMDocument object

When you process an XML document, the first step is to create a DOMDocument object. You do this using the toDOMDocument function, which takes a string as an argument and returns a DOMDocument object.

The following lines create a DOMDocument object from an XML document named mydoc.xml stored in a Web site:

xmlDoc = site.GetDocument( "mydoc.xml" );
domDoc = toDOMDocument( xmlDoc.source );

The first line creates a document object, the second line creates a DOMDocument object, taking a string as an argument.

You can create DOMDocuments from several other sources. For information on generating XML documents, see "Creating XML documents".

You can also create an empty DOMDocument object and add elements to it using the DOM interface. For more information, see "Using the DOM interface to create and edit XML documents".

Parser does not validate

The toDOMDocument function parses the XML document and builds a representation of the entire document tree in memory. The XML parser is not a validating parser: that is, it does not confirm that the structure of the document conforms to any DTD referenced in the document.

On the other hand, if the document is not well formed, then it cannot be built into a proper tree structure, and the function call fails, returning null. You can call site.GetErrorInfo to display specific error information.

In this example, the error is handled by writing a message and stopping the application:

domDoc = toDOMDocument( xmlDoc.source );
if( domDoc == null ){
document.writeln( site.GetErrorInfo() );
exit;
}

Performance tip

Parsing large documents with toDOMDocument can be an expensive task. Consider designing your site so that it is carried out as infrequently as possible.

You can avoid unnecessary parsing of the document by attaching the DOMDocument object to the session object, using a script such as:

function getSessionDocument(){
if ( !exists(session.domDoc) ) {
xmlDoc = site.GetDocument( "xmldoc.xml" );
session.domDoc = toDOMDocument( xmlDoc.source );
}
return session.domDoc
}

If you call this function whenever you need the DOM representation of the XML document, it is regenerated when necessary, but not if it already exists in the session object.

 


Copyright © 1999 Sybase, Inc. All rights reserved.