Summary:
See also: The Genero Web Services XML Extension Library
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.
xml.DomDocument
Class Methods | |
Name | Description |
xml.DomDocument.create()
RETURNING xml.DomDocument
|
Constructor of an empty DomDocument object; returns a DomDocument object. |
xml.DomDocument.createDocument(
|
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( 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("fjs","List","http://www.mysite.com/xmlapi")
Produces:
<fjs:List xmlns:fjs="http://www.mysite.com/xmlapi">
[...]
</fjs:List>Create a DomDocument with an initial root node named List with
fjs
as the prefix andhttp://www.mysite.com/xmlapi
as the namespace.
Object Methods | |
Name | Description |
getDocumentElement() |
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( 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(
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. Note: 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( 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. Note: 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(
|
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.Note: If the namespaces list is NULL, the prefixes and namespaces defined in the document itself are used if available. Note: 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(
RETURNING xml.DomNode
|
Returns the Element that has an attribute of type ID with the given value, or NULL if there is none. Note: 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".
Object Methods | |
Name | Description |
importNode(
|
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. Note: Document and Document Type nodes cannot be imported. Throws an exception in case of errors, and updates status with an error code. |
clone() |
Returns a copy of this DomDocument object, or NULL. |
appendDocumentNode(
|
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. Note: 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( |
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.
Note: 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(
|
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. Note: 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(
|
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. Note: 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( |
Removes a child DomNode object from the DomNode children for this DomDocument object,
where node is the node to remove. Note: 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(
|
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. |
Object Methods | |
Name | Description |
createNode(
|
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(
|
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(| |
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(
|
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. Note: 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(
|
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. Note: 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(
|
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. Note: 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(
|
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. Note: 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( |
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. Note: 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( |
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. Note: 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( |
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. Note: 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( |
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. Note: Only internal DTDs are supported. Note: 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() |
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 notxmlns: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.
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(
|
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. Note: 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. Note: See setFeature() to specify how the document can be loaded.Note: 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(
|
Loads an XML Document into a DomDocument object from a string
where str is the string to load. (Not part of W3C API). Note: See setFeature() to specify how the document can be loaded.Note: 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( |
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. Note: 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. Note: See setFeature() to specify how the document can be saved.Note: 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()
|
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). Note: See setFeature() to specify how the document can be saved.Note: 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")
where
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")
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 nodeselt
and threetextnode
.
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")
where
save("http://myserver:8080/data/save1.xml")
save("file:///data/save.xml")
save("tcp://localhost:4242/")
save("alias://test")
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.
Object Methods | |
Name | Description |
setFeature( |
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( |
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()
|
Returns the document version as defined in the XML document declaration, which is 1.0. No other versions are supported. |
getXmlEncoding()
|
Returns the document encoding as defined in the XML document declaration, or NULL if there is none. |
setXmlEncoding( |
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()
|
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(
|
Sets the XML standalone attribute in the XML declaration to yes or no in the XML declaration, or NULL. |
Object Methods | |
Name | Description |
validate()
|
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. Note: See setFeature() to specify what kind of validation to do.Note: 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(
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. Note: See setFeature() to specify what kind of validation to do.Note: 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. |
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(
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.
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.
Feature | Description |
format-pretty-print | Formats the output by adding white space to produce a pretty-printed, indented, human-readable form. Note: Default value is FALSE. |
comments | Defines whether the XML comments are kept during the load of a document into a DomDocument object. Note: 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. Note: 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. Note: 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. Note: default value is TRUE. |
validation-type | Defines what kind of validation should be performed. Note: 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. Note: 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.4js.com mySchema2.xsd" |
external-noNamespaceSchemaLocation | Defines a list of XML schemas to use for validation on a DomDocument object. Note: Value is a space-separated string of one or several strings representing the location of a schema. Example : "mySchema1.xsd mySchema2.xsd" |
schema-uriRecovery | Resolves or changes the location of an XML schema referenced by import tags and namespace URIs in other schemas. Note: Value is a space-separated string of one or several pairs of strings representing the namespace URI to recover, followed by its location. Example: "http://tempuri/org/NS myFile.xsd http://www.4js.com myFJS.xsd" |
To get 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 ?> |
You must write following code: IMPORT xml MAIN DEFINE doc xml.DomDocument DEFINE pi xml.DomNode DEFINE node xml.DomNode DEFINE elt xml.DomNode # Create a document with an initial namespace qualified root node LET doc = xml.DomDocument.CreateNS("MyPre","RootNode","http://www.tempuri.org") # Create a Processing instruction LET pi = doc.createProcessingInstruction("Target1,"This is my first PI") # And add it at the begining of the document CALL doc.prependDocumentNode(pi) # Create another Processing instruction LET pi = doc.createProcessingInstruction("Target2,"This is my last PI") # And add it at the end of the document CALL doc.appendDocumentNode(pi) # Retrieve initial root node of the document LET elt = doc.getDocumentElement() # Create a new Element node LET node = doc.createElement("MyPre","Element","http://www.tempuri.org") # And add it as child of the RootNode CALL elt.appendChild(node) # Then save the document on disk CALL doc.save("MyFile.xml") END MAIN |
Following code loads one or more XML schemas or uses an embedded DTD to validate against a XML document: IMPORT xml MAIN DEFINE location STRING DEFINE xmlfile STRING DEFINE doc xml.DomDocument DEFINE ind INTEGER IF num_args()<2 THEN # Checks the number of arguments CALL ExitHelp() ELSE LET doc = xml.DomDocument.Create() LET xmlfile = arg_val(num_args()) IF num_args() == 2 AND arg_val(1) == "-dtd" THEN # User choosed DTD validation CALL doc.setFeature("validation-type","DTD") ELSE # User choosed XML Schema validation IF arg_val(1) == "-ns" THEN # Handle namespace qualified XML schemas IF num_args() MOD 2 != 0 THEN CALL ExitHelp() END IF FOR ind = 2 TO num_args()-1 STEP 2 IF location IS NULL THEN LET location = arg_val(ind) || " " || arg_val(ind+1) ELSE LET location = location || " " || arg_val(ind) || " " || arg_val(ind+1) END IF END FOR TRY CALL doc.setFeature("external-schemaLocation",location) CATCH FOR ind = 1 TO doc.getErrorsCount() DISPLAY "Schema error ("||ind||") :",doc.getErrorDescription(ind) END FOR EXIT PROGRAM (-1) END TRY ELSE # Handle unqualified XML schemas FOR ind = 1 TO num_args()-1 IF location IS NULL THEN LET location = arg_val(ind) ELSE LET location = location || " " || arg_val(ind) END IF END FOR TRY CALL doc.setFeature("external-noNamespaceSchemaLocation",location) CATCH FOR ind = 1 TO doc.getErrorsCount() DISPLAY "Schema error ("||ind||") :",doc.getErrorDescription(ind) END FOR EXIT PROGRAM (-1) END TRY END IF END IF END IF TRY # Load XML document from disk CALL doc.load(xmlfile) CATCH # Display errors if loading failed IF doc.getErrorsCount()>0 THEN FOR ind = 1 TO doc.getErrorsCount() DISPLAY "LOADING ERROR #"||ind||" :",doc.getErrorDescription(ind) END FOR EXIT PROGRAM(-1) ELSE DISPLAY "Unable to load file :",xmlfile EXIT PROGRAM(-1) END IF END TRY TRY # Validate loaded document LET ind = doc.validate() IF ind == 0 THEN # Successful validation DISPLAY "OK" ELSE # Display validation errors FOR ind = 1 TO doc.getErrorsCount() DISPLAY "VALIDATING ERROR #"||ind||" :",doc.getErrorDescription(ind) END FOR EXIT PROGRAM(-1) END IF CATCH DISPLAY "Unable to validate file :",xmlfile EXIT PROGRAM(-1) END TRY END MAIN # Display help FUNCTION ExitHelp() DISPLAY "Validator < -dtd | -ns [namespace schema]+ | [schema]+ > xmlfile" EXIT PROGRAM 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 |