How to Create an XML File From a Database Using VB
- 1). Create a database connection. Before you can retrieve information from the database, you need to create a connection object. The code below creates a connection to an Access database named "myServer":
Dim conn as OleDbConnection
conn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source="myDB.mdb") - 2). Create a query and retrieve information from the database. This is used to populate the XML file. In this sample, the first and last name is retrieved from the customer table. A datareader is used to store results from your database. The code below queries the database and assigns the results to a datareader object:
conn.Open()
query ="select customerId,first_name,last_name from customer"
command =New OleDbCommand(query,conn)
reader=dbcomm.ExecuteReader() - 3). Create a new XML file and create the start tag. The start tag is the root of your XML document. Therefore, for this example, since the XML document is a list of customers, the root tag is "customer." The code below illustrates how to start an XML document to write records:
Dim xml As New XmlTextWriter("customer.xml", System.Text.Encoding.UTF8)
xml.WriteStartDocument(True)
xml.Formatting = Formatting.Indented
xml.Indentation = 2
xml.WriteStartElement("customer") - 4). Fill in the XML file with each customer record. The code below shows you how to loop through the reader and write each record to the XML file:
Do while reader.Read()
xml.WriteStartElement(reader(0))
xml.WriteString(reader(1))
xml.WriteString(reader(2))
Loop - 5). Close the document by writing the end tag to the XML file. The following code ends the document and closes the XML document, so you can use it in another application:
xml.WriteEndElement()
xml.WriteEndDocument()
xml.Close()
Source...