Building an XML Document
Before getting into the specifics of the logic or script, a brief overview of building the XML document may prevent us from being mired in detail.
To programmatically create an XML document, we use the Document Object Model (DOM) exposed by MSXML2.DOMDocument.
The first step is to load a root element. All XML documents are required to a have single root element node, which is the parent for all other element nodes. There are two ways of creating the root element:
Loading in a string with the loadXML command
Reading in a file with the load command
Our sample program uses the loadXML command with a constant containing the XML prologue and the first element:
wwdiary: :"<?xml version='1.0' ?><wwdiary></wwdiary>"
Next, we focus on the recurring action of building element nodes. We create the empty element by using the CreateElement command of the document object DOMDocument. For those elements that have attributes, we create a nodeMap object by using the Attributes command and call the program-specific subroutine createandAppendAttribute subroutine to create and append the name/value pair for each attribute.
Finally, the newly created element must be connected to its parent element node to become part of the overall structure. We do this using the appendChild command with the parent node.
Listing 1 illustrates the sequence involved in creating the exerciseEntryNode.
Listing 1 Code To Create the exerciseEntry Node
Set exerciseEntryNode = oXMLDoc.createElement("exerciseEntry") Set objNodeMap = exerciseEntryNode.Attributes createandAppendAttribute oXMLDoc, objNodeMap, "Activity", strActivity createandAppendAttribute oXMLDoc, objNodeMap, "Duration", strDuration createandAppendAttribute oXMLDoc, objNodeMap, "Intensity", strIntensity createandAppendAttribute oXMLDoc, objNodeMap, "Points", strPoints dayNode.appendChild (exerciseEntryNode)
The variables beginning with str (strActivity, strDuration, strIntensity, and strPoints) contain text strings.
The createandAppendAttribute subroutine simply creates an attribute object by using the createAttribute method of the document object. Next, it populates the object with the name/value attribute pair. Finally, it calls the setNamedItem function of the nodeMap object to append the attribute to the nodeMap object (see Listing 2).
Listing 2 Code for the createandAppendAttribute Function
Public Function createandAppendAttribute(objDoc, nodeMap, attrName, attrValue) Dim objAttribute Set objAttribute = objDoc.createAttribute(attrName) objAttribute.Value = attrValue nodeMap.setNamedItem objAttribute End Function