following code demonstrates how we can write a collection to an XML file using C#

we can do it in two ways first lets do it without using serilization.



public static void writetoXML(string fileName)
{
DataSet ds = new DataSet("ds01"); //root node
DataTable t = new DataTable("table01"); //
DataColumn qNo = new DataColumn("questionNo"); //
DataColumn ans = new DataColumn("answer"); //

t.Columns.Add(qNo); //add columns to the table
t.Columns.Add(ans);
ds.Tables.Add(t); //add table to the dataset

DataRow r;
int qLimit = 10;
for (int i = 0; i <>
{
r = t.NewRow(); //create a new row of type table
r["questionNo"] = i;
r["answer"] = "answer for question" + i;
t.Rows.Add(r); //add the newly populated row to the table
}

//write the added data to the console
Console.WriteLine("Data added to the table\n");
Console.WriteLine("QuestionNo\t\tAnswer");
Console.WriteLine("--------------------------------------------");
for (int i = 0; i <>
{
Console.WriteLine(t.Rows[i][0].ToString()+"\t\t|\t"+t.Rows[i][1].ToString());
}
ds.WriteXml(fileName);
}

lets rewrite it again using serilization there is a big advantage in this i'll show it right away
when using serialization we write the data using a XMLSerializer object which will be created using the method typeof(). this allows us to write any type of collection to a XML file with little altering of code as possible
lets see how the above method will look like when written using serilization

public static void serializeDatSet(string fileName)
{
//create a new XMLSerializer object of type DataSet
XmlSerializer ser = new XmlSerializer(typeof(DataSet));

DataSet ds = new DataSet("ds01");
DataTable t = new DataTable("table01");
DataColumn qNo = new DataColumn("questionNo");
DataColumn ans = new DataColumn("answer");

t.Columns.Add(qNo);
t.Columns.Add(ans);
ds.Tables.Add(t);

DataRow r;
int qLimit = 10;
for (int i = 0; i <>
{
r = t.NewRow();
r["questionNo"] = i;
r["answer"] = "answer for question" + i;
t.Rows.Add(r);
}

Console.WriteLine("Data added to the table\n");
Console.WriteLine("QuestionNo\t\tAnswer");
Console.WriteLine("--------------------------------------------");
for (int i = 0; i <>
{
Console.WriteLine(t.Rows[i][0].ToString()+"\t\t|\t"+t.Rows[i][1].ToString());
}
TextWriter writer=new StreamWriter(fileName);

//write the data set to the writer stream using the serialization object
ser.Serialize(writer,ds);

writer.Close();

}

so lets say you want to write an ArrayList to a XML file
well see the code below

public static void writeToXML(string fileName)
{
ArrayList arr = new ArrayList();
for (int i = 0; i <>
{
arr.Add("answer for question" + i);
}
XmlSerializer ser = new XmlSerializer(typeof(ArrayList));
TextWriter writer = new StreamWriter(fileName);
ser.Serialize(writer, arr);
writer.Close();
}