shahab
May 16th, 2002, 03:09 AM
Can anyone tell how to write an xml file through VB.
Jerry Grant
May 16th, 2002, 10:36 AM
This is just a quick example....
But includes all the basic objects, elements, attributes, comment, and Processing Instruction. This example could be adapted to include a loop to create multiple Person elements using an array or something similar.
Enjoy!
Public Sub XMLwriteDemo()
'=== XML document objects
Dim objXMLdoc As Object
Dim objXMLpi As Object
Dim objComment As Object
Dim objXMLroot As Object
Dim objXMLchild As Object
Dim objXMLtext As Object
'=== Create document
Set objXMLdoc = CreateXMLDoc
'=== Create processing instruction so file can be parsed
Set objXMLpi = objXMLdoc.createProcessingInstruction("xml", "version='1.0' encoding='utf-8'")
objXMLdoc.appendChild objXMLpi
'== Add a comment
Set objComment = objXMLdoc.createComment("Example by Jerry Grant - www.jg-design.net " & Now)
objXMLdoc.appendChild objComment
'=== Create the main Root
Set objXMLroot = objXMLdoc.createElement("Addresses")
objXMLdoc.appendChild objXMLroot
'=== Add an element 'Person'
Set objXMLchild = objXMLdoc.createNode("element", "Person", "")
'=== Give it an 'id' attribute
objXMLchild.setAttribute "id", 1
objXMLdoc.documentElement.appendChild objXMLchild
'=== Add a Surname element
Set objXMLtext = objXMLdoc.createNode("element", "Surname", "")
objXMLtext.Text = "Grant"
objXMLchild.appendChild objXMLtext
'=== Add a Forename element
Set objXMLtext = objXMLdoc.createNode("element", "Forename", "")
objXMLtext.Text = "Jerry"
objXMLchild.appendChild objXMLtext
'=== Add a Link element
Set objXMLtext = objXMLdoc.createNode("element", "Link", "")
objXMLtext.Text = "http://www.jg-design.net"
objXMLchild.appendChild objXMLtext
'=== Save as a file
objXMLdoc.Save App.Path & "\JG-Design.xml"
'=== Destroy objects
Set objXMLtext = Nothing
Set objXMLchild = Nothing
Set objXMLroot = Nothing
Set objComment = Nothing
Set objXMLpi = Nothing
Set objXMLdoc = Nothing
End Sub
Public Function CreateXMLDoc() As Object
'=== Late bound example
Set CreateXMLDoc = CreateObject("Msxml2.DOMDocument")
'=== Uncomment for early bound example
'Set CreateXMLDoc = New MSXML2.DOMDocument
With CreateXMLDoc
.preserveWhiteSpace = False
.resolveExternals = False
.validateOnParse = False
.async = False
End With
End Function