Converting DataTable to XML using Memory Stream


In this article we are going to look at how to convert a DataTable into XML using Memory Stream. We are going to use the WriteXml method of DataSet reference class to convert datatable to XML. If the requirement is to access and store the data in memory instead of Hard Disk or a Network Connection then we go for Memory Stream.

In this article we are going to look at how to convert a DataTable into XML using Memory Stream. We are going to use the WriteXml method of DataSet reference class to convert datatable to xml. If the requirement is to access and store the data in memory instead of Hard Disk or a Network Connection then we go for Memory Stream.

Step1: Create a DataTable with two columns: id and name. Add some rows to the datatable as shown in the below code:


DataTable dtTest = new DataTable("Employee");
dtTest.Columns.Add("id", typeof(int));
dtTest.Columns.Add("name", typeof(string));
dtTest.Rows.Add(1, "sakshi");
dtTest.Rows.Add(2, "rekha");


Step2:Create a MemoryStream object:

MemoryStream mstrm = new MemoryStream();


Step3:Create a class "DataSetSerializer" which is used to convert the memory stream to xml.

using System.Text;
using System.Data;
using System.IO;
public class DataSetSerializer
{
public static void WriteDataTable(DataTable dt, Stream stm,
XmlWriteMode mode)
{
DataSet tmp = CreateTempDataSet(dt);
tmp.WriteXml(stm, mode);
}

private static DataSet CreateTempDataSet(DataTable dt)
{
// Create a temporary DataSet
DataSet ds = new DataSet("Employees");
ds.Tables.Add(dt.Copy());
return ds;
}
}


Step4: Call the WriteDataTable method of DataSetSerializer class. This method in turn calls "CreateTempDataSet" method which adds the DataTable to the DataSet and returns the DataSet. This is done to create DataSet as we can only create xml out of the DataSet. Then we are saving the resultant xml from the memory stream into the "result" variable.

DataSetSerializer.WriteDataTable(dtTest, mstrm, XmlWriteMode.IgnoreSchema);
string result = Encoding.UTF8.GetString(mstrm.GetBuffer(), 0, (int)mstrm.Length);

now result is a variable which contains the data of the datatable "Employee" in xml format. as shown below:


<Employees>
<Employee>
<id>1</id>
<name>sakshi</name>
</Employee>
<Employee>
<id>2</id>
<name>rekha</name>
</Employee>
</Employees>


Article by Vaishali Jain
Miss. Jain Microsoft Certified Technology Specialist in .Net(Windows and Web Based application development)

Follow Vaishali Jain or read 127 articles authored by Vaishali Jain

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: