Thursday 30 January 2014

Write and Read XML file from datatable in C#

Hello guys,
Today i am sharing my code with you for writing and reading XML file
from datatable.

Fill the datatable with data first from database or any other source.

eg. datatabel named "Student" is loaded datatable.

Now write this data into XML and then read that XML file into another new datatable.

string path = string.Concat(AppDomain.CurrentDomain.BaseDirectory, @"StudentData\");

Here "StudentData" is my folder name in my project solution.

String fileName = path + Guid.NewGuid() + ".xml";

This is file name with full path.
Here is used Guid to give filename, you can use anything you like here.

Now create file

var fs = File.Create(fileName);

Above code will create the file in a specified folder eg. StudentData here.

Now its time to write XML file.

ds.Tables[0].WriteXml(fileName, XmlWriteMode.WriteSchema);

Above code will write the data with schema in xml file.
Why this? Because when you use writexml method with file name only then it'll write only data into the file on with schema.

When you read XML into datatabl at that time you must have new datatable with schema that's why i wrote the above code that write the XML file with schema.

Now its time to read XML file.

DataTable Newdt = new DataTable();

That's it. Hope this help you...
Thanks... Enjoy coading...

No comments:

Post a Comment