ARTICLE

Generating XML from SQL Database

Posted by Shivani Articles | Visual Basic 2010 July 01, 2003
This sample shows how you can obtain a Dataset from (in this case) a SQL Server database, and then write it out to an XML Document. As an "Extra Added Bonus(tm)", it can show you how to write the schema as well.
 
Reader Level:

Description

This sample shows how you can obtain a Dataset from (in this case) a SQL Server database, and then write it out to an XML Document. As an "Extra Added Bonus(tm)", it can show you how to write the schema as well. The SQL Server database in question is the venerable and useful Northwind database.

The significant parameters are all declared at the beginning as strings, so that you can easily debug and tweak for your own usage. In this section, we create a connection string, a query string (in standard SQL) and specify a target filename.

Then, we call the function,

Shared Sub writeSQLQueryToFileAsXML(ByVal connString As String, ByVal query As String, ByVal filename As String)

This function first gets a connection, creates an adapter and specifies the connection and command to run through it, then obtains a dataset from that adapter.

This function then shows how you can write that DataSet out to a stream (in this case, a FileStream) as an XML document through the DataSet member, public void WriteXml(Stream). And if you've got some extra time on your hands, you can even uncomment the code in the last section, to write the DataSet's SCHEMA to a file!

An interesting corollary to this example would be to stream the DataSet's XML out to an HTTPResponse's HTTPWriter.outputStream, but that is both the subject of another sample, and also perhaps more easily done through native SQL Server capabilities.

Note that the XML that is written is output as a fragment, that is, there is no element, <?xml version="1.0"?> at the beginning, nor is there a unifying, single root node. While you will have to add both of these, this is really a sensible choice. First of all, only you, and your particular application context, can say what is the right name for the root node - is it <DelinquentCustomers>, or <GoldStarCustomers>? Secondly, it may be a node or set of nodes buried down inside a much larger document, such as a <Contacts> node under one of several <Salesman> nodes. Get the picture?

Compiling and Running the code:

vbc XMLGenFromSQLDbPB.vb.
Or
vbc /r:System.dll,System.Data.dll,System.Xml.dll  XMLGenFromSQLDbPB.vb.

This will return you with the location where it had saved the XML file.You can specify it in the String s.

Source Code:

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, ByVal filename 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()
'***************************************************

Login to add your contents and source code to this article
share this article :
post comment
 

i am creating xml file frm databse as above but the output i get is not in the proper format as nodes, elemnts & sub elemnts needes to be grouped morre
how can it be done thr' code

Posted by S VK Nov 18, 2010

hello

I have seen your article titled " Generating XML from SQL Database by Shivani Jul 01, 2003   "

I was very delighted because this is really what i am looking for.  I am trying to use xml in my program that has to retrieve thousands of records. I am currently putting these values in a session variable but i think i have to persist it in an xml rather than in a session variable for performance purposes.

This is my code based on your code.

Dim ObjConn As New SqlConnection(ConfigurationSettings.AppSettings("strConnection"))

Dim ObjAdapter = New SqlDataAdapter(String.Format("strProcTemp '{0}'", "12"), ObjConn)
Dim ObjDataset As New DataSet
ObjAdapter.Fill(ObjDataset, "XXX")
Dim ObjDataTable As DataTable = ObjDataset.Tables("XXX")

Dim myFs As FileStream = Nothing
myFs = New FileStream("D:\myXML" + ".xml", FileMode.OpenOrCreate, FileAccess.Write)
ObjDataset.WriteXml(myFs)
myFs.Close()

 

This is the error generated.

Access to the path "D:\myXML.xml" is denied.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.UnauthorizedAccessException: Access to the path "D:\myXML.xml" is denied.

ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.

To grant ASP.NET write access to a file, right-click the file in Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.

Source Error:

Line 46: 
Line 47:         Dim myFs As FileStream = Nothing
Line 48:         myFs = New FileStream("D:\myXML" + ".xml", FileMode.OpenOrCreate, FileAccess.Write)
Line 49:         ' Apply the WriteXml method to write an XML document
Line 50:         ObjDataset.WriteXml(myFs)

 

Could you please tell me or better yet show me what my code is doing wrong?

More power to you!

Posted by razel guinid Jan 12, 2006
Nevron Diagram
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Become a Sponsor