XML is very well integrated with .NET. Many server controls have XML methods built in making XML capabilities only a method or two away. The DataSet class contains several of these XML methods and we will examine a couple of them in this article. The task in this example is to read a database table into a DataSet and then write the DataSet out to the file system as an XML file. We will also do the same thing with the schema for the XML file.
The code is ridiculously simple! Our .aspx file, as a matter of fact contains essentially no code other than the bare minimum for an html page. All we have done is add a Done! message to it. The work, what there is of it, is done in the code-behind file. The .aspx file is shown below.
|
<%@ Page Language="vb" Src="DataSetToXML.aspx.vb" Inherits="DataSetToXML" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>DataSetToXML</title> <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0"> <meta name="CODE_LANGUAGE" content="Visual Basic 7.0"> <meta name=vs_defaultClientScript content="JavaScript"> <meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5"> </head> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> </form> <h3>Done!</h3> </body> </html> |
The code-behind file is not much more complicated. Most of it is the usual code for filling a DataSet using a DataAdapter. To keep the XML file to a shorter length we are selecting only the TOP 10 from the Customers table of the Northwind database. The two lines that actually write out the XML file and the Schema are highlighted in blue. WriteXML and WriteXMLSchema are both methods of the DataSet class. Server.MapPath is utilized to write the two files to the root directory of your web. The two files are named "Customers.xml" and "Custmers.xsd".
|
Imports System Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Public Class DataSetToXML : Inherits System.Web.UI.Page Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim objConn As SqlConnection Dim strSql As String strSql = "SELECT TOP 10 * FROM Customers" objConn = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString")) Dim sdaCust As New SqlDataAdapter(strSql, objConn) Dim dstCust As New DataSet() sdaCust.Fill(dstCust, "Customers") 'Save data to xml file and schema file dstCust.WriteXML(Server.MapPath("Customers.xml"),XmlWriteMode.IgnoreSchema) dstCust.WriteXMLSchema(Server.MapPath("Customers.xsd")) End Sub End Class |
I started to apologize for the brevity of this article, but really, .Net is to blame for making it so easy to convert database tables to XML! I hope you agree.
You may download the code here.