Saturday, August 14, 2010

Writing Data from a database to an XML Document

 

Using XML and ADO.NET mode, reading a database and writing to an XML document and vice versa is not a big deal. In this section of this article, you will see how to read a database table's data and write the contents to an XML document.

The DataSet class provides method to read a relational database table and write this table to an XML file. You use Write Xml method to write a dataset data to an XML file. 

In this sample example, I have used commonly used Northwind database comes with Office 2000 and later versions. You can use any database you want. Only thing you need to do is just chapter the connection string and SELECT SQ L query.

In this sample, I reate a data adapter object and selects all records of Customers table. After that I can fill method to fill a dataset from the data adapter.

 

In this sample example, I have used OldDb data provides. You need to add reference to the Syste.Data.OldDb namespace to use OldDb data adapters in your program. As you can see: first I create a connection with northwind database using OldDbConnection. After that I create a data adapter object by passing a SELECT SQL query and connection. Once you have a data adapter, you can fill a dataset object using Fill method of the data adapter. Then you can WriteXml method of DataSet, which creates an XML document and write its contents to the XML document. In our sample, we read Customers table records and write DataSet contents to OutputXml.Xml file in C:\ dir.

using System;

using System.Xml;

using System.Data;

using System.Data.OleDb;

namespace ReadingXML2

{

class Class1

{

static void Main(string[] args)

{

// create a connection

OleDbConnection con = new OleDbConnection();

con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";

// create a data adapter

OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", con);

// create a new dataset

DataSet ds = new DataSet();

// fill dataset

da.Fill(ds, "Customers");

// write dataset contents to an xml file by calling WriteXml method

ds.WriteXml("C:\\OutputXML.xml");

}

}

}


For more information please Visit:

CSharpCorner.com

Search This Blog