The DOMDocument
object exposes the createNode
method, which allows you to create a qualified node by supplying the node type, name, and namespaceURI
of the new node.
DOMDocument
also exposes the following eight methods, which allow you to create specific Document Object Model (DOM) nodes.
These methods return objects and interfaces and are described in the XML Reference. These specific objects and interfaces expose properties and methods associated with that node. For example, the following sample code assigns an XMLDOMElement
object with the name of "item"
to the variable xmlElem
.
xmlElem = xmlDoc.createElement("item")
You can then add an attribute to that element by calling the setAttribute
method and passing that method a string containing the attribute name and a string containing the attribute value.
xmlElem.setAttribute("id","bar")
Using books.xml again as an example, the following code creates a new element, PAGES
, and uses the appendChild
method to add it to the second child node of the root, COLLECTION
. It then sets the text
property for the new element to "400"
.
Dim xmlDoc Dim root Dim newElem Set xmlDoc = CreateObject("Msxml2.DOMDocument.5.0") xmlDoc.async = False xmlDoc.load("c:\books.xml") If (xmlDoc.parseError.errorCode <> 0) Then Dim myErr Set myErr = xmlDoc.parseError MsgBox("You have error " & myErr.reason) Else Set root = xmlDoc.documentElement Set newElem = xmlDoc.createElement("PAGES") root.childNodes.item(1).appendChild newElem root.childNodes.item(1).lastChild.text = "400" MsgBox root.childNodes.item(1).xml End If
You can assign a new document to a document object by assigning the document a new root element using the documentElement
property.
XMLDoc.documentElement = XMLNode
In order for this operation to work, XMLNode
must be an element type node.
Note Assigning the document object a new document element does not change the other children of the document. For example, the doctype
element does not change.
Accessing the Document Tree | appendChild Method | createNode Method | documentElement Property | setAttribute Method | XML Reference