Create and modify XML Dom

speakers_86

Registered User.
Local time
Today, 13:31
Joined
May 17, 2007
Messages
1,919
After HOURS of researching, I finally got two usable sub routines. Requires reference to MSXML. This library is huge, that's why this was so hard for me. Ultimately, this will be a part of my ribbon builder.

Code:
Option Compare Database
Option Explicit


Sub test()
    Dim objdom As DOMDocument
    Dim objRootElem As IXMLDOMElement

    Set objdom = New DOMDocument

    ' Creates root element
    Set objRootElem = objdom.CreateElement("Books")
    objdom.appendChild objRootElem

    CreateNode "Books", "Authors", objdom
    CreateNode "Books/Authors", "IDField", objdom
    CreateAttrib "Books/Authors/IDField", "Author", "Arthur C. Clarke", objdom

    ' Saves XML data to disk.
    objdom.Save ("C:\Users\Kanyer\Desktop\test.xml")
    Set objdom = Nothing
    Set objRootElem = Nothing
End Sub
Code:
Private Sub CreateAttrib(strNode As String, strAttrib As String, strValue As String, objdom As DOMDocument)
    'Create an attribute in the specified dom and node
    'Parameters
    '    strNode    enter the name of the node to modify
    '    strAttrib  enter the name of your attribute
    '    strValue   enter the value the attribute will assume
    '    objdom     reference to the document
    'Adapted from http://www.freevbcode.com/ShowCode.asp?ID=1919
    'by speakers_86
    
    Dim attrib As IXMLDOMAttribute
    Set attrib = objdom.createAttribute(strAttrib)
    attrib.nodeValue = strValue
    Dim node   As IXMLDOMElement
    Set node = objdom.selectSingleNode(strNode)

    objdom.createAttribute (strAttrib)
    node.setAttributeNode attrib

    Set node = Nothing
    Set attrib = Nothing
End Sub
Code:
Private Sub CreateNode(strParent As String, strNode As String, objdom As DOMDocument)
    'Add a node to the specified dom
    'Parameters
    '   strParent   node will be created as a child of this node
    '   strNode     basename of your node; ex. <strNode\>
    '   objdom      reference to the document
    'Adapted from http://www.freevbcode.com/ShowCode.asp?ID=1919
    'by speakers_86
     
    Dim node   As IXMLDOMNode
    Dim parent As IXMLDOMElement
    Set parent = objdom.selectSingleNode(strParent)
    Set node = objdom.CreateElement(strNode)
    parent.appendChild node

    Set parent = Nothing
    Set node = Nothing
End Sub


Output:
Code:
<Books><Authors><IDField Author="Arthur C. Clarke"/></Authors></Books>
 

Users who are viewing this thread

Back
Top Bottom