Peter Bosch is the Principal of Highpoint Software Systems, L.L.C., where he works to help companies reap the benefits of leading edge development. This avocation dates back to 1991 when he taught C and C++ to a group at Lockheed Martin (then GE Aerospace) migrating from Ada, and continued in 1996 when he was a technical lead on a group that brought Java scalability, flexibility and portability to GE Medical Systems' MRI group. He is now working on several contracts, and looking for the next great opportunity to help an organization evolve into the C# and .Net spaces. [Pete Bosch] He can be reached at [email protected].
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,
static void writeSQLQueryToFileAsXML(string connString,string query,string filename);
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:
csc XMLGenFromSQLDbPB.cs
Or
csc /r:System.dll,System.Data.dll,System.Xml.dll XMLGenFromSQLDbPB.cs
Join the conversation! Your thoughts help the community grow.