如何在VB.NET中从SQL数据库生成XML?

时间:2015-08-11 09:49:06

标签: sql-server vb.net

如何使用从(在本例中)SQL Server数据库获取的数据集生成XML,然后将其写入XML文档?

1 个答案:

答案 0 :(得分:2)

Imports System
Imports System.Data
Imports System.Xml
Imports System.Data.SqlClient
Imports System.IO
Namespace WriteXML
    Public Class WriteXML
        Shared Sub Main()

            ' NOTE : YOU WILL NEED TO HAVE SQL SERVER (or MSDE) AVAILABLE, AND
            ' YOU WILL NEED THE NORTHWIND DATABASE INSTALLED IN THE SQL SERVER
            ' INSTANCE IN ORDER FOR THIS TO WORK. 
            ' MODIFY THE FOLLOWING CONNECTION STRING AND QUERY STRING TO RUN
            ' THIS SAMPLE AGAINST A DIFFERENT DATABASE AND/OR QUERY.

            Dim outputFileName As String = "C:/myXmlData" ' ".xml" will be appended.
            Dim connString As String = "user id=sa;password=password;" + "Database=northwind;server=(local);"
            Dim sqlQueryString As String = "SELECT * FROM Suppliers"
            ' Here's the meat of the demonstration.
            writeSQLQueryToFileAsXML(connString, sqlQueryString, outputFileName)
            Console.WriteLine("Wrote query results to {0}", outputFileName)
        End Sub 
        //Main
        Shared Sub writeSQLQueryToFileAsXML(ByVal connString As String, ByVal query As String, ByValfilename As String)
            Dim myConn As New SqlConnection(connString)
            Dim adapter As New SqlDataAdapter
            adapter.SelectCommand = New SqlCommand(query, myConn)
            ' Build the DataSet
            Dim myDs As New DataSet
            adapter.Fill(myDs)
            Dim myFs As FileStream = Nothing
            ' Get a FileStream object
            myFs = New FileStream(filename + ".xml", FileMode.OpenOrCreate, FileAccess.Write)
            ' Apply the WriteXml method to write an XML document
            myDs.WriteXml(myFs)
            ' It is always good housekeeping to close a file.
            myFs.Close()
        End Sub 'writeSQLQueryToFileAsXML 
    End Class 'WriteXML '***************************************************
End Namespace 'WriteXML ' Uncomment the following code if you also want to
' dump the DataSet's schema to a file...
'***************************************************
' Get a FileStream object
myFs = new FileStream(filename + "_Schema.xml", FileMode.OpenOrCreate, FileAccess.Write)
myDs.WriteXmlSchema(myFs)
' It is always good housekeeping to close a file.
myFs.Close()
'********************************************