Back to Contents


The DomDocument class

Summary:

See also: The Genero Web Services XML Library


Syntax

The DomDocument class provides methods to manipulate a data tree, following the DOM standards.

The status is set to zero after a successful method call.

Syntax

xml.DomDocument
 

Methods


Creation methods

Class Methods
Name Description
xml.DomDocument.create()
   RETURNING xml.DomDocument
Constructor of an empty DomDocument object; returns a DomDocument object.
xml.DomDocument.createDocument(
  name STRING )
   RETURNING xml.DomDocument
Constructor of a DomDocument with an XML root element; where name is the name of the XML Element.
Returns a DomDocument object or NULL.
Throws an exception in case of errors, and updates status with an error code.
xml.DomDocument.createDocumentNS(
  prefix STRING,
  name STRING,
  ns STRING )
   RETURNING xml.DomDocument
Constructor of a DomDocument with a root namespace-qualified XML root element where prefix is the prefix of the XML Element or NULL, name is the name of the XML Element, and ns is the namespace of the XML Element. Returns a DomDocument object.
Throws an exception in case of errors, and updates status with an error code.

Usage

xml.domDocument.create()

Create a DomDocument without a root node.

xml.domDocument.create("ARoot")

Create a DomDocument with an initial root node named ARoot.

xml.domdocument.createDocumentNS("abc","List","http://www.mysite.com/xmlapi")

Produces:
<abc:List xmlns:abc="http://www.mysite.com/xmlapi">
[...]
</abc:List>

Create a DomDocument with an initial root node named List with abc as the prefix and http://www.mysite.com/xmlapi as the namespace.

Back to the top


Navigation methods

Object Methods
Name Description
getDocumentElement()
   RETURNING xml.DomNode
Returns the root XML Element DomNode object for this DomDocument object. Returns a DomNode object, or NULL.
getFirstDocumentNode()
   RETURNING xml.DomNode
Returns the first child DomNode object for this DomDocument object, or NULL.
getLastDocumentNode()
   RETURNING xml.DomNode
Returns the last child DomNode object for this DomDocument object, or NULL.
getDocumentNodesCount()
   RETURNING INTEGER
Returns the number of child DomNode objects for this DomDocument object.
getDocumentNodeItem(
  pos INTEGER )
   RETURNING xml.DomNode
Returns the child DomNode object at a given position for this DomDocument object where pos is the position of the node to return (Index starts at 1), or NULL.
Throws an exception in case of errors, and updates status with an error code.
getElementsByTagName(
  name STRING )
   RETURNING xml.DomNodeList
Returns a DomNodeList object containing all XML Element DomNode objects with the same tag name in the entire document; name is the name of the XML Element tag to match, or "*" to match all tags.  Returns a DomNodeList object, or NULL.
The returned list is ordered using a Depth-First pass algorithm.
Throws an exception in case of errors, and updates status with an error code.
getElementsByTagNameNS(
  name STRING,
  ns STRING )
   RETURNING xml.DomNodeList
Returns a DomNodeList object containing all namespace qualified XML Element DomNode objects with the same tag name and namespace in the entire document; name is the name of the XML Element tag to match, or "*" to match all tags; ns is the namespace URI of the XML Element tag to match, or "*" to match all namespaces.  Returns a DomNodeList object, or NULL.
The returned list is ordered using a Depth-First pass algorithm.
Throws an exception in case of errors, and updates status with an error code.
selectByXPath(
  expr STRING,
  NamespacesList ... )
   RETURNING xml.DomNodeList
Returns a DomNodeList object containing all DomNode objects matching an XPath 1.0 expression (Not part of W3C API); expr is the XPath 1.0 expression, NamespacesList is a list of prefixes bounded to namespaces in order to resolve qualified names in the XPath expression. This list must be filled with an even number of arguments, representing the prefix and its corresponding namespace.
Examples :
selectByXPath("//d:Record", "d", "http://defaultnamespace")
selectByXPath("//ns1:Record", NULL)
selectByXPath("//ns1:Records/ns2:Record", "ns1", "http://namespace1", "ns2", "http://namespace2")
selectByXPath("//ns1:Record", "ns1") is invalid because the namespace definition is missing.
If the namespaces list is NULL, the prefixes and namespaces defined in the document itself are used if available.
A namespace must be an absolute URI (ex 'http://', 'file://').
Throws an exception in case of errors, and updates status with an error code.
getElementById(
  id STRING )
   RETURNING xml.DomNode
Returns the Element that has an attribute of type ID with the given value, or NULL if there is none.
Attributes with the name "ID" or "id" are not of type ID unless so defined with setIdAttribute or setIdAttributeNS. However, there is a specific attribute called xml:id and belonging to the namespace http://www.w3.org/XML/1998/namespace that is always of type ID even if not set with setIdAttributeNS.
Throws an exception in case of errors, and updates status with an error code.

Usage

DomDocument navigation functions deal with nodes immediately under the DomDocument object, except for search features. To navigate through all the nodes, you can refer to the navigation functions of the class xml.DomNode.

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="card.xsl"?>
<!-- demo card -->
<CardList xml:id="1" >[...]
</CardList>

The first node of the document is xml-stylesheet. Use getFirstDocumentNode to get the node.
The element at position 2 is the comment <!-- demo card -->. Use getDocumentNodeItem function to get the node.
The last node of the document is CardList. Use getLastDocumentNode to get the node.
The number of node of the document is 3. This is result of function getDocumentNodesCount. This function only count the number of children immediately under the DomDocument.
Note that the first line of the example, <?xml version="1.0" encoding="ISO-8859-1"?>, is not considered as a node. To access to the information of the first line, use getXmlVersion and getXmlEncoding functions.
Caution, if the example is in pretty printed format, the results are not the same. There are addition text nodes representing the carriage returns.

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="card.xsl"?>
<!-- demo card -->
<CardList xml:id="1" >
[...]
</CardList>

See Cautions section for more details.

You can select nodes using their tag names, by XPath, or by their attributes value (if of type ID, xml:id for example). The getElementsbyTagName and getElementsbyTagNameNS methods return a DomNodeList object, unlike the other methods that return a DomNode object. The DomNodeList is restricted to contain objects with the same tag name and/or namespace. The selectByXPath method also returns a DomNodeList object, but each node can have a different name.

getElementsByTagNameNS("message","http://schemas.xmlsoap.org/wsdl/")

Get the message nodes that have http://schemas.xmlsoap.org/wsdl/ as the namespace.

getElementsByTagNameNS("message","*")

Get all the message nodes, regardless of the namespace they have.

getElementsByTagName("message")

Get all the message nodes that do not have any namespace.

selectByXPath("//xs:element",NULL)

Get all the xs:element nodes that has a namespace corresponding to prefix xs.

selectByXPath("//Card",NULL)

Get all the Card nodes that do not have any namespace.

getElementById("1")

Get the unique node whose attribute of type ID has a value of "1".

Back to the top


Management methods

Object Methods
Name Description
importNode(
  node xml.DomNode,
  deep INTEGER )
   RETURNING xml.DomNode
Imports a DomNode from a DomDocument object into this DomDocument object, where node is the node to import. When deep is FALSE only the node is imported; when TRUE the node and all its child nodes are imported. Returns the DomNode object that has been imported to this DomDocument, or NULL.
Document and Document Type nodes cannot be imported.
Throws an exception in case of errors, and updates status with an error code.
clone()
   RETURNING xml.DomDocument
Returns a copy of this DomDocument object, or NULL.
appendDocumentNode(
   node xml.DomNode )
Adds a child DomNode object to the end of the DomNode children for this DomDocument object, where node is the node to add. Status is updated with an error code.
Only Text nodes, Processing Instruction nodes, Document Fragment nodes, one Element node and one Document Type node allowed.
Throws an exception in case of errors, and updates status with an error code.
prependDocumentNode(
  node xml.DomNode )
Adds a child DomNode object to the beginning of the DomNode children for this DomDocument object (Not part of W3C API); node is the node to add.
Only Text nodes, Processing Instruction nodes, Document Fragment nodes, one Element node and one Document Type node allowed.
Throws an exception in case of errors, and updates status with an error code.
insertBeforeDocumentNode(
  node xml.DomNode,
  ref xml.DomNode )
Inserts a child DomNode object before another child DomNode for this DomDocument object;.node is the node to insert, ref is the reference node - the node before which the new node must be inserted.
Only Text nodes, Processing Instruction nodes, Document Fragment nodes, one Element node and one Document Type node allowed.
Throws an exception in case of errors, and updates status with an error code.
insertAfterDocumentNode(
  node xml.DomNode,
  ref xml.DomNode )
Inserts a child DomNode object after another child DomNode for this DomDocument object (Not part of W3C API); node is the node to insert; ref is the reference node - the node after which the new node must be inserted.
Only Text nodes, Processing Instruction nodes, Document Fragment nodes, one Element node and one Document Type node allowed.
Throws an exception in case of errors, and updates status with an error code.
removeDocumentNode(
  node xml.DomNode )
Removes a child DomNode object from the DomNode children for this DomDocument object, where node is the node to remove.
Only Text nodes, Processing Instruction nodes, Element nodes and Document Type nodes allowed.
Throws an exception in case of errors, and updates status with an error code.
declareNamespace(
  node xml.DomNode,
  alias STRING,
  ns STRING )
Forces namespace declaration to an XML Element DomNode for this DomDocument object (Not part of W3C API); node is the XML Element DomNode that carries the namespace definition; alias is the alias of the namespace to declare, or NULL to declare the default namespace; ns is the URI of the namespace to declare (can only be NULL if alias is NULL).
Throws an exception in case of errors, and updates status with an error code.

Back to the top


Node creation methods

Object Methods
Name Description
createNode(
  str STRING )
   RETURNING
xml.DomNode
Creates an XML DomNode object from a string for this DomDocument object (not part of W3C API); str is the string representation of the DomNode to be created.  Returns a DomNode object, or NULL.
Throws an exception in case of errors, and updates status with an error code.
createElement(
  name STRING )
   RETURNING xml.DomNode
Creates an XML Element DomNode object for this DomDocument object, where name is the name of the XML element, cannot be NULL. Returns a DomNode object, or NULL.
Throws an exception in case of errors, and updates status with an error code.
createElementNS(|
  prefix STRING,
  name STRING,
  ns STRING)
   RETURNING xml.DomNode
Creates an XML namespace-qualified Element DomNode object for this DomDocument object, where prefix is the prefix of the XML element, or NULL to use the default namespace; name is the name of the XML element, cannot be NULL; ns is the namespace URI of the XML element, cannot be NULL. Returns a DomNode object, or NULL.
Throws an exception in case of errors, and updates status with an error code.
createAttribute(
  name STRING )
   RETURNING xml.DomNode
Creates an XML Attribute DomNode object for a DomDocument object, where name is the name of the XML attribute, cannot be NULL. Returns a DomNode object, or NULL.
To create a default namespace declaration attribute use xmlns as the name. (Using declareNamespace instead is recommended.)
Throws an exception in case of errors, and updates status with an error code.
createAttributeNS(
  prefix STRING,
  name STRING,
  ns STRING )
   RETURNING xml.DomNode
Creates an XML namespace-qualified Attribute DomNode object for this DomDocument object, where prefix is the prefix of the XML attribute, cannot be NULL; name is the name of the XML attribute, cannot be NULL; ns is the namespace URI of The XML attribute, cannot be NULL. Returns a DomNode object, or NULL.
To create a namespace declaration attribute use xmlns as the prefix and http://www.w3.org/XML/1998/namespace as the namespace. (Using declareNamespace instead is recommended.)
Throws an exception in case of errors, and updates status with an error code.
createTextNode(
  text STRING )
   RETURNING xml.DomNode
Creates an XML Text DomNode object for this DomDocument object, where text is the data of the XML Text node, or NULL.  Returns a DomNode object, or NULL.
Only the characters #x9, #xA, #xD, [#x20-#xD7FF], [#xE000-#xFFFD] and [#x10000-#x10FFFF] are allowed in the content of an XML Text node. The saveToFile() and normalize() methods will fail if characters other than those allowed exist in a Text node.
createComment(
  comment STRING )
   RETURNING xml.DomNode
Creates an XML Comment DomNode object for this DomDocument object, where comment is the data of the XML Comment node, or NULL. Returns a DomNode object, or NULL.
Only the characters #x9, #xA, #xD, [#x20-#xD7FF], [#xE000-#xFFFD] and [#x10000-#x10FFFF]  are allowed in the content of an XML Comment node.
The character sequence (Double-Hyphen) '--' is not allowed in the content of an XML Comment node. The saveToFile() and normalize() methods will fail if this sequence or characters other than those allowed exist in a Comment node.
createCDATASection(
  cdata STRING )
   RETURNING xml.DomNode
Creates an XML CData DomNode object for this DomDocument object, where cdata is the data of the XML CData node, or NULL. Returns a DomNode object, or NULL.
Only the characters #x9, #xA, #xD, [#x20-#xD7FF], [#xE000-#xFFFD] and [#x10000-#x10FFFF] are allowed in the content of an XML CDATASection node.
The character sequence (Double-Hyphen) '--' is not allowed in the content of an XML CDATASection node. The saveToFile() and normalize() methods will fail if this sequence or characters other than those allowed exist in a CDATASection node.
createEntityReference(
  ref STRING )
   RETURNING xml.DomNode
Creates an XML EntityReference DomNode object for this DomDocument object, where ref is the name of the entity reference Returns a DomNode object, or NULL.
An Entity Reference node is read-only and cannot be modified.
Throws an exception in case of errors, and updates status with an error code.
createProcessingInstruction(
  target STRING,
  data STRING )
   RETURNING xml.DomNode
Creates an XML Processing Instruction DomNode object for this DomDocument object, where target is the target part of the XML Processing Instruction, cannot be NULL; data is the data part of the XML Processing Instruction, or NULL.  Returns a DomNode object, or NULL.
Only the characters #x9, #xA, #xD, [#x20-#xD7FF], [#xE000-#xFFFD] and [#x10000-#x10FFFF] are allowed in the content of an XML Processing Instruction node.
The character sequence (Double-Hyphen) '--' is not allowed in the content of an XML Processing Instruction. The saveToFile() and normalize() methods will fail if this sequence or characters other than those allowed exist in a Processing Instruction node.
Throws an exception in case of errors, and updates status with an error code.
createDocumentType(
  name STRING,
  publicID STRING,
  systemID STRING,
  internalDTD STRING )
   RETURNING xml.DomNode
Creates an XML Document Type (DTD) DomNode object for this DomDocument object (Not part of W3C API); name is the name of the document type; publicId is the URI of the public identifier or NULL;  systemId is the URL of the system identifier or NULL (Specifies the file location of the external DTD subset); internalDTD is the internal DTD subset or NULL. Returns a DomNode object, or NULL if internalDTD is malformed.
Only internal DTDs are supported.
The public identifier cannot be set without the system identifier.
Throws an exception in case of errors, and updates status with an error code.
createDocumentFragment()
   RETURNING xml.DomNode
Creates an XML Document Fragment DomNode object for this DomDocument object. Returns a DomNode object, or NULL.

Usage

Creating a node for the DomDocument are done in two steps:

Each time you create a node you need to append it at the right place in the DomDocument. To add a node the document use the DomDocument management methods or the DomNode manipulation methods.

createNode("<LastName>PATTERSON</LastName><FirstName>Andrew</FirstName>")

Creates a structure of nodes.

createElement("CardList")

Produces
<CardList>

createElementNS("cny", "Company", "http://www.mysite.com/")

Produces
<cny:Company xmlns:cny="http://www.mysite.com/" /> or <cny:Company />. See Cautions for more details.

createAttribute("Country")

Creates a Country attribute node.
To set a value to the attribute use the method setNodeValue of the xml.DomNomde class. To add the attribute to an element node use the method setAttributeNode of the xml.DomNode class.

createAttributeNS("tw","Town","http://www.mysite.com/cities")

Produces
xmlns:tw="http://www.mysite.com/cities" tw:Town=""
To set a value to the attribute use the method setNodeValue of the xml.DomNomde class. To add the attribute to an element node use the method setAttributeNodeNS of the xml.DomNode class. For optimization reasons, the namespace is not written aside the attribute until the saving of the DomDocument. When accessing the element node, the namespace is not listed in the list of children. In the example above, tw:Town="" is in the list of children not xmlns:tw="http://www.mysite.com/cities". To access the namespace during the DomDocument building use the method normalize first. Normalize write the namespace declaration at the appropriate place. If there is no previous declaration, it will be accessible as an attribute of this element otherwise it will be an attribute of one of the ancestors of the element.

createTextNode("My Company")

Creates a text node.

createComment("End of the card")

Produces
<!--End of the card-->

createCDATASection("<website><a href=\"www.mysite.com\">My Company</a></website>")

Produces
<![CDATA[<website><a href="www.mysite.com">My Company</a></website>]]>

createEntityReference("title")

Creates the entity reference &title.

createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"card.xsl\"")

Produces
<?xml-stylesheet type="text/xsl" href="card.xsl"?>

createDocumentType("Card", NULL, NULL,"<!ELEMENT Card (lastname, firstname, company, location)>")

Produces
<!DOCTYPE Card [ <!ELEMENT Card (lastname , firstname , company , location)>]>
Only inline DTD are supported. The DTD has to been inserted in the DomDocument at an appropriate place.

createDocumentFragment

Is a method that creates a lighweight DomDocument. It represents a sub-tree of nodes that do not need to conform to well-formed XML rules. This makes DocumentFragment easier to manipulate than a DomDocument.


for i=1 to 5
  let node = doc.createelement("Card")
  call root.appendchild(node)
end for

This produces a sub-tree with 5 Card nodes that do not have any root node. Once the sub-tree is completed, it can be added to the DomDocument object like any other node.

Back to the top


Load and save methods

Object Methods
Name Description
normalize() Normalizes the entire Document. This method merges adjacent Text nodes, removes empty Text nodes and sets namespace declarations as if the document had been saved.
See getErrorsCount() and getErrorDescription() to retrieve error messages related to XML document normalization.
Throws an exception in case of errors, and updates status with an error code.
load(
  url STRING )
Loads an XML Document into a DomDocument object from a file or an URL,  where url is a valid URL or the name of the file.
Only the following kinds of URLs are supported: http://, https://, tcp://, tcps://, file:/// and alias://. See FGLPROFILE Configuration for more details about URL mapping with aliases, and for proxy and security configuration.
See setFeature() to specify how the document can be loaded.
See getErrorsCount() and getErrorDescription() to retrieve error messages related to XML document loading.
Throws an exception in case of errors, and updates status with an error code.
loadFromString(
  str STRING )
Loads an XML Document into a DomDocument object from a string where str is the string to load. (Not part of W3C API).
See setFeature() to specify how the document can be loaded.
See getErrorsCount() and getErrorDescription() to retrieve error messages related to XML document loading.
Throws an exception in case of errors, and updates status with an error code.
loadFromPipe(
 cmd STRING )
Loads an XML Document into a DomDocument object from a PIPE where cmd is the command to read from the PIPE. (Not part of W3C API).
See setFeature() to specify how the document can be loaded.
See getErrorsCount() and getErrorDescription() to retrieve error messages related to XML document loading.
Throws an exception in case of errors, and updates status with an error code.
save(
  url STRING )
Saves a DomDocument object as an XML Document to a file or URL, where url is a valid URL or the name of the file.
Only the following kinds of URLs are supported: http://, https://, tcp://, tcps://, file:/// and alias://. See FGLPROFILE Configuration for more details about URL mapping with aliases, and for proxy and security configuration.
See setFeature() to specify how the document can be saved.
See getErrorsCount() and getErrorDescription() to retrieve error messages related to XML document saving.
Throws an exception in case of errors, and updates status with an error code.
saveToString()
   RETURNING STRING
Saves a DomDocument object as an XML Document to a string. Returns the string that will contain the resulting document. (Not part of W3C API).
See setFeature() to specify how the document can be saved.
See getErrorsCount() and getErrorDescription() to retrieve error messages related to XML document saving.
Throws an exception in case of errors, and updates status with an error code.
saveToPipe(
  cmd STRING )
Saves a DomDocument object as an XML Document to a PIPE, where cmd is the command to start the pipe.
See setFeature() to specify how the document can be saved.
See getErrorsCount() and getErrorDescription() to retrieve error messages related to XML document saving.
Throws an exception in case of errors, and updates status with an error code.

Usage

You can load an existing xml document. Before loading an xml document you need to create the DomDocument object.

A DomDocument can load files using different URI: http://, https://, tcp://, tcps://, file:// and alias://. Use getErrorsCount() and getErrorDescription() to display errors about the document loading.

load("data.xml")
load("http://www.w3schools.com/xml/cd_catalog.xml")
load("https://localhost:6394/ws/r/calculator?WSDL")
load("file:///data/cd_catalog.xml")
load("tcp://localhost:4242/")
load("tcps://localhost:4243/")
load("alias://demo")
where demo alias is defined in fglprofile as ws.demo.url = "http://www.w3schools.com/xml/cd_catalog.xml"

loadfromstring("<List> <elt>First element</elt> <elt>Second element</elt> <elt>Third element</elt> </List>")

Produces a sub-tree with a root node List and three nodes elt and three textnode.

A DomDocument can be saved at different URI begining with: http://, https://, tcp://, tcps://, file:// and alias://. Use getErrorsCount() and getErrorDescription() to display errors about the document saving.

save("myfile.xml")
save("http://myserver:8080/data/save1.xml")
save("file:///data/save.xml")
save("tcp://localhost:4242/")
save("alias://test")
where test alias is defined in fglprofile as ws.test.url = "http://localhost:8080/data/save3.xml"

saveToString saves the DomDocument in a string. Use getErrorsCount() and getErrorDescription()to display errors about the document saving

normalize function emulates a DomDocument save and load. It can be called at any stage of the DomDocument building. This removes empty Text nodes and sets namespace declarations as if the document had been saved.

Back to the top


Configuration methods

Object Methods
Name Description
setFeature(
  feature STRING,
  value STRING)
Sets a feature for the DomDocument object, where feature is the name of a DomDocument Feature, and value is the value of a feature.
Throws an exception in case of errors, and updates status with an error code.
getFeature(
  feature STRING)
   RETURNING STRING
Gets a feature for the DomDocument object, where feature is the name of the DomDocument Feature. Returns the value of the feature.
Throws an exception in case of errors, and updates status with an error code.
getXmlVersion()
   RETURNING STRING
Returns the document version as defined in the XML document declaration, which is 1.0. No other versions are supported.
getXmlEncoding()
   RETURNING STRING
 
Returns the document encoding as defined in the XML document declaration, or NULL if there is none.
setXmlEncoding(
  enc STRING )
Sets the XML document encoding in the XML declaration, or NULL.
Throws an exception in case of errors, and updates status with an error code.
isXmlStandalone()
   RETURNING INTEGER
Returns whether the XML standalone attribute is set in the XML declaration. Returns TRUE if the standalone attribute in the XML declaration is set to yes.
setXmlStandalone(
  alone INTEGER )
Sets the XML standalone attribute in the XML declaration to yes or no in the XML declaration, or NULL.

Back to the top


Validation methods

Object Methods
Name Description
validate()
   RETURNING INTEGER
Performs a DTD or XML Schema validation for this DomDocument object (Not part of W3C API). Returns the number of validation errors, or zero if there are none.
See setFeature() to specify what kind of validation to do.
See getErrorsCount() and getErrorDescription()to retrieve error messages related to validation errors.
Throws an exception in case of errors, and updates status with an error code.
validateOneElement(
  elt xml.DomNode )
  
RETURNING INTEGER
Performs a DTD or XML Schema validation of an XML Element DomNode object (Not part of W3C API)node is the XML Element DomNode to validate. Returns the number of validation errors, or zero if there are none.
See setFeature() to specify what kind of validation to do.
See getErrorsCount() and getErrorDescription() to retrieve error messages related to validation errors.
Throws an exception in case of errors, and updates status with an error code.

Back to the top


Error management methods

Object Methods
Name Description
getErrorsCount()
  
RETURNING INTEGER
Returns the number of errors encountered during the loading, the saving or the validation of an XML document (Not part of W3C API). Returns the number of errors, or zero if there are none.
getErrorDescription(
  pos INTEGER )
  
RETURNING STRING
Returns the error description at given position (Not part of W3C API)pos is the position of the error description (index starts at 1). Returns a string with an error description.
Throws an exception in case of errors, and updates status with an error code.

Usage

for i=1 to doc.getErrorsCount()
  display "[", i, "] ", doc.getErrorDescription(i)
end for

Displays all the errors encountered in the save, load or validate of doc DomDocument.

To display other errors, use the global variable status to get the error code and err_get(status) or sqlca.sqlerrm to get the description of the error. See error code for more details.

Back to the top


Cautions

Whitespaces, line feeds and carriage returns between elements are represented as text nodes in memory. An XML document written in a single line and a human readable (pretty printed format) do not have the same representation in the DomDocument. Take this under account when navigating in the document.

If a DomNode is not attached to a DomDocument and not referenced by any variable it can be destroyed. If one child of this node is still referenced, this child is not destroyed but its parent and the others node of the sub-tree are destroyed. To check if a node is attached to a DomDocument use isAttached method.

DomDocument remains in memory if any of its node is still referenced in a variable.

Back to the top


DomDocument Features

Name Description
format-pretty-print Formats the output by adding white space to produce a pretty-printed, indented, human-readable form.
Default value is FALSE.
comments Defines whether the XML comments are kept during the load of a document into a DomDocument object.
Default value is TRUE.
whitespace-in-element-content Defines whether XML Text nodes that can be considered "Ignorable" are kept during the load of an XML document into a DomDocument object.
Default value is TRUE.
cdata-sections Defines whether XML CData nodes are kept or replaced by XML Text nodes during the load of an XML document into a DomDocument object.
Default value is TRUE.
expand-entity-references Defines whether XML EntityReference nodes are kept or replaced during the load of an XML document into a DomDocument object.
Default value is TRUE.
validation-type Defines what kind of validation should be performed.
Only DTD and Schema are allowed. Default is Schema.
external-schemaLocation Defines a list of namespace-qualified XML schemas to use for validation on a DomDocument object.
Value is a space-separated string of one or several pairs of strings representing the namespace URI of the schema, followed by its location.
Example:  "http://tempuri/org/NS  mySchema1.xsd  http://www.mycompany.com  mySchema2.xsd"
external-noNamespaceSchemaLocation Defines a list of XML schemas to use for validation on a DomDocument object.
Value is a space-separated string of one or several strings representing the location of a schema.
Example:  "mySchema1.xsd  mySchema2.xsd"
schema-uriRecovery Changes the schema location of an XML schema referenced by import tags in other schemas.
Value is a space-separated string of one or several pairs of strings representing the original schema location followed by the new schema location.
Example:  "http://www.w3.org/2001/xml.xsd  myXML.xsd  http://www.mycompany.com/GWS.xsd  myGWS.xsd"


Examples

Example 1 : Create a namespace qualified document with processing instructions

To save the following XML document on disk:

 <?Target1 This is my first PI ?>
<MyPre:RootNode xmlns:MyPre="http://www.tempuri.org" >
<MyPre:Element />
</MyPre:RootNode>
<?Target2 This is my last PI ?>br>

Write the following code:

01 IMPORT xml
02
03 MAIN
04 DEFINE doc xml.DomDocument
05   DEFINE pi xml.DomNode
06   DEFINE node xml.DomNode
07   DEFINE elt xml.DomNode
08
09   # Create a document with an initial namespace qualified root node
10   LET doc = xml.DomDocument.CreateNS("MyPre", "RootNode", "http://www.tempuri.org")
11   # Create a Processing instruction
12   LET pi = doc.createProcessingInstruction("Target1", "This is my first PI")
13   # And add it at the begining of the document
14   CALL doc.prependDocumentNode(pi)
15   # Create another Processing instruction
16   LET pi = doc.createProcessingInstruction("Target2", "This is my last PI")
17   # And add it at the end of the document
18   CALL doc.appendDocumentNode(pi)
19   # Retrieve initial root node of the document
20   LET elt = doc.getDocumentElement()
21   # Create a new Element node
22   LET node = doc.createElement("MyPre", "Element", "http://www.tempuri.org")
23   # And add it as child of the RootNode
24   CALL elt.appendChild(node)
25   # Then save the document on disk
26   CALL doc.save("MyFile.xml")
27 END MAIN

Example 2 : Validating a document against XML schemas or a DTD

Following code loads one or more XML schemas or uses an embedded DTD to validate against a XML document:

 
01 IMPORT xml
02
03 MAIN
04   DEFINE location STRING
05   DEFINE xmlfile STRING
06   DEFINE doc xml.DomDocument
07   DEFINE ind INTEGER
08
09   IF num_args()<2 THEN
10    # Checks the number of arguments
11     CALL ExitHelp()
12   ELSE
13     LET doc = xml.DomDocument.Create()
14     LET xmlfile = arg_val(num_args())
15     IF num_args() == 2 AND arg_val(1) == "-dtd" THEN
16      # User choosed DTD validation
17       CALL doc.setFeature("validation-type", "DTD")
18     ELSE
19       # User choosed XML Schema validation
20       IF arg_val(1) == "-ns" THEN
21        # Handle namespace qualified XML schemas
22         IF num_args() MOD 2 != 0 THEN
23          CALL ExitHelp()
24         END IF
25         FOR ind = 2 TO num_args()-1 STEP 2
26          IF location IS NULL THEN
27            LET location = arg_val(ind) || " " || arg_val(ind+1)
28           ELSE
29             LET location = location || " " || arg_val(ind) || " " || arg_val(ind+1)
30           END IF
31         END FOR
32         TRY
33          CALL doc.setFeature("external-schemaLocation", location)
34         CATCH
35          FOR ind = 1 TO doc.getErrorsCount()
36            DISPLAY "Schema error ("||ind||") :",doc.getErrorDescription(ind)
37           END FOR
38           EXIT PROGRAM (-1)
39         END TRY
40       ELSE
41         # Handle unqualified XML schemas
42         FOR ind = 1 TO num_args()-1
43         IF location IS NULL THEN
44           LET location = arg_val(ind)
45           ELSE
46           LET location = location || " " || arg_val(ind)
47           END IF
48         END FOR
49         TRY
50         CALL doc.setFeature("external-noNamespaceSchemaLocation", location)
51         CATCH
52         FOR ind = 1 TO doc.getErrorsCount()
53           DISPLAY "Schema error ("||ind||") :",doc.getErrorDescription(ind)
54          END FOR
55         EXIT PROGRAM (-1)
56        END TRY
57       END IF
58     END IF
59   END IF
60   TRY
61     # Load XML document from disk
62     CALL doc.load(xmlfile)
63   CATCH
64    # Display errors if loading failed
65    IF doc.getErrorsCount()>0 THEN
66     FOR ind = 1 TO doc.getErrorsCount()
67       DISPLAY "LOADING ERROR #"||ind||" :",doc.getErrorDescription(ind)
68      END FOR
69     EXIT PROGRAM(-1)
70    ELSE
71     DISPLAY "Unable to load file :",xmlfile
72      EXIT PROGRAM(-1)
73    END IF
74   END TRY
75   TRY
76    # Validate loaded document    
77 LET ind = doc.validate()
78     IF ind == 0 THEN
79     # Successful validation
80     DISPLAY "OK"
81     ELSE
82     # Display validation errors
83     FOR ind = 1 TO doc.getErrorsCount()
84       DISPLAY "VALIDATING ERROR #"||ind||" :",doc.getErrorDescription(ind)
85      END FOR
86     EXIT PROGRAM(-1)
87     END IF
88 CATCH
89   DISPLAY "Unable to validate file :",xmlfile
90    EXIT PROGRAM(-1)
91   END TRY
92 END MAIN
93 # Display help
94 FUNCTION ExitHelp()
95   DISPLAY "Validator < -dtd | -ns [namespace schema]+ | [schema]+ > xmlfile"
96 EXIT PROGRAM
97 END FUNCTION

Examples

$ fglrun Validator -dtd MyFile.xml

Validates XML file using DTD embedded in the XML file

$ fglrun Validator Schema1.xsd Schema2.xsd MyFile.xml

Validates unqualified XML file using two unqualified XML schemas

$ fglrun Validator -ns http://tempuri.org/one Schema1.xsd http://tempuri.org/two Schema2.xsd MyFile.xml

Validates namespace qualified XML file using two namespace qualified XML schemas

Back to the top