Use the Xml Web Control to Display Database Query Results as XML...
By: John Kilgo Date: January 21, 2003 Download the code.


Sometime you may need to query a database and produce the results as an XML file. The .Net XML Web Control makes this extremely easy to do. All you have to do is create an instance of the XML control on your .aspx page. A very few lines of code can then be used to display the database query as XML. To show you how easy this is, note the aspx file immediately below - two lines of code, counting the @Page directive!
<%@ Page Language="vb" Src="DisplayXmlFromQuery.aspx.vb" Inherits="DisplayXml" %>

<asp:xml id="xmlControl" runat="server" />
The code-behind file is not a whole lot more complicated. Most of it is the usual connect to the database and fill a DataSet type of code. The last three lines of the Page_Load sub-routine is where all the work gets done. First we set the DataSet's name property to whatever we want. This will be the root node of the XML file. We then dimension an XmlDataDocument (xmlDoc) with the DataSet as the source. Lastly, we set the Document property of our Xml Web Control to the XmlDataDocument. That's all there is to it.
Imports System
Imports System.Xml
Imports System.Data
Imports System.Data.SqlClient

Public Class DisplayXml : Inherits System.Web.UI.Page

  Public xmlControl As System.Web.UI.WebControls.Xml

  Sub Page_Load(sender As Object, e As EventArgs)
    Dim objConn As SqlConnection
    Dim ds As New DataSet()
    objConn = New SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=secret;")
    Dim dataAdapter As New SqlDataAdapter("Select Top 10 * From Customers", objConn)

    dataAdapter.Fill(ds, "Customers")
    ds.DataSetName = "CustomerListing"
    Dim xmlDoc As XmlDataDocument = New XmlDataDocument(ds)
    xmlControl.Document = xmlDoc
  End Sub

End Class
You may download the code here.