How To Generate A XML File With Access VBA

XML is used to structure your data. You can send a CSV file to another person, but
using XML, you can structure your data in a more elegant format, and get very specific
about your fields, and what data is contained within your tags (your field names).

This is different than a basic CSV file where you don’t have that ability.

You can essentially provide instructions to the receiving tool on how to handle the
information they have received.

Using HTML you have specific tags you can use, so you are limited, but with XML you can customize your tags,
and you can display that data file on a webpage.

In this post you are going to be able to generate an XML file with the data from your database.

For example, I need to transfer my database information to my scanning devices so the field team
can finish their inspections, away from the office. So I’ll generate an XML file which I can email and load
into their scanning device.

Private Sub btnXML_Click()
    Dim strSQL As String
    Dim rst As Recordset
    
    strSQL = "SELECT ID, Description, [Income/Expense], Taxable FROM Categories"
    
    Set rst = CurrentDb.OpenRecordset(strSQL)
    
    strpath = CurrentProject.Path & "\CategoryList.xml"
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    Dim objFile As Object
    Set objFile = fso.CreateTextFile(strpath, True, True)
    
    objFile.Write "<?xml version='1.0'?>" & vbCrLf
    objFile.Write "<Categories>" & vbCrLf
    
    Do Until rst.EOF
        
        objFile.Write "<ID>" & rst.Fields("ID") & "</ID>" & vbCrLf
        objFile.Write "<Description>" & rst.Fields("Description") & "</Description>" & vbCrLf
        objFile.Write "<IncomeExpense>" & rst.Fields("Income/Expense") & "</IncomeExpense>" & vbCrLf
        objFile.Write "<Taxable>" & rst.Fields("Taxable") & "</Taxable>" & vbCrLf
        
        rst.MoveNext
    Loop
    
    objFile.Write "</Categories>"
    
    rst.Close
    Set rst = Nothing
    
    MsgBox "Complete"
End Sub

Here is the resulting file CategoryList.xml in same path your database is in:




Comments are closed.