Create XML with schema/namespace references via API
September 27, 2010 Leave a comment
UV 10.2
Under UniVerse 10.2, there are no API functions that will add Namespace or Schema attributes to a node. This makes it more difficult, but not impossible, to create an XML document that contains Namespace or Schema references.
The Normal approach
To create a simple XML document via API calls is very straight forward:
- Create root DOM using XDOMCreateRoot()
- Add root node using XDOMCreateNode() and XDOMAddChild()
- Build XML using root node
The Steps needed
To create an XML document that contains Namespace or Schema references needs the following steps to be performed:
- Create an XML string of the root node containing the Namespace and/or Schema reference
- Create DOM using XDOMOpen() by supplying the XML string and using the XML.FROM.STRING location option.
- Obtain a reference to the root node using XDOMLocate()
- Build XML using root node
Example
We need to create the following XML document:
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
<name>John Doe</name>
</card>
Step 1
Create the XML string containing the namespace and/or schema references:
$include UNIVERSE.INCLUDE XML.H
root.XML = ‘<card xmlns=“http://businesscard.org” ‘
root.XML := ‘xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” ‘
root.XML := ‘xsi:schemaLocation=“http://businesscard.org businesscard.xsd”></card>‘
Step 2
Create DOM handle using the XML string:
xmlStat = XDOMOpen( root.XML, XML.FROM.STRING, root.DOM)
Step 3
Obtain a reference to the root node
map.NS = ‘xmlns:a=http://businesscard.org xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance’
xmlStat = XDOMLocate( root.DOM, “/a:card”, map.NS, card.NODE)
Step 4
The node card.NODE can now be used to build the rest of the XML document:
xmlStat = XDOMCreateNode( card.NODE, “name”, “”, XDOM.ELEMENT.NODE, name.NODE)
xmlStat = XDOMAddChild( card.NODE, “”, map.NS, name.NODE, XDOM.NODUP)
xmlStat = XDOMCreateNode( name.NODE, “”, “John Doe”, XDOM.TEXT.NODE, text.NODE)
xmlStat = XDOMAddChild( name.NODE, “”, map.NS, text.NODE, XDOM.NODUP)
xmlStat = XDOMWrite( root.DOM, final.XML, XML.TO.STRING)
CRT “XML = [“:final.XML:”]”
Output from the above example should be:
XML = [<card xmlns=”http://businesscard.org” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://businesscard.org businesscard.xsd”><name>John Doe</name></card>
]
The key is Steps 1-3, which result in an XML document that contains the necessary namespace and/or schema references.