theDeSilva.com Andrew de Silva

VB.NET Database query return result as XML

January 25th, 2010 · No Comments · .NET

A simple VB.NET page that takes a ID variable and return the result as XML page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
 
Imports System.IO
Imports System.Xml
Imports System.Data
Imports System.Data.SqlClient
 
Partial Class writeXML
    Inherits System.Web.UI.Page
 
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        GetXML(Request.QueryString("pid"))
    End Sub
 
    Public Function sqlConnect() As SqlConnection
        Dim oCn As SqlConnection = New SqlConnection("Data Source=xxxx\xxxx; Initial Catalog=tableName; User Id=dbUSERNAME; Password=dbPASSWORD")
        Return oCn
    End Function
 
    Private Function GetDataSet(ByVal strSQL As String) As DataSet
 
        '1. Create a connection
        Dim myConnection As SqlConnection = sqlConnect()
 
        '2. Create the command object, passing in the SQL string    
        Dim myCommand As New SqlCommand(strSQL, myConnection)
 
        myConnection.Open()
 
        '3. Create the DataAdapter
        Dim myDataAdapter As New SqlDataAdapter()
        myDataAdapter.SelectCommand = myCommand
 
 
        '4. Populate the DataSet and close the connection
        Dim myDataSet As New DataSet()
        myDataAdapter.Fill(myDataSet)
        myConnection.Close()
 
        'Return the DataSet
        Return myDataSet
 
    End Function
 
 
    Public Sub GetXML(ByVal id As String)
 
        Dim sqlCommand As String
 
        sqlCommand = "SELECT column1, column2  "
        sqlCommand &= "FROM tableName "
        sqlCommand &= "WHERE id = '" & id & "';  "
 
        Dim retrievedDataSet As New DataSet
        retrievedDataSet = GetDataSet(sqlCommand)
 
        Dim xmlDocument As XmlDocument = New XmlDocument
        xmlDocument.LoadXml(retrievedDataSet.GetXml)
 
 
        Response.Clear()
        Response.ContentType = "text/xml"
        Response.ContentEncoding = Encoding.UTF8
        Response.Write(xmlDocument.InnerXml)
        Response.Flush()
        Response.End()
 
    End Sub
 
End Class
Share and Enjoy:
  • Digg
  • StumbleUpon
  • del.icio.us
  • Reddit
  • Technorati
  • Facebook
  • Google Bookmarks
  • LinkedIn

Tags: ···