Wednesday, 23 April 2014

Convert text file to XML file

Convert text file to XML file


protected void Button1_Click(object sender, EventArgs e)
{
//Convert text file to XML file
char strDelimiter = '\t';
string strFilePath = "c:/Test.txt";
DataSet oDS = new DataSet();
DataTable oTable = new DataTable();
DataRow oRows;
int intCounter = 0;
oDS.DataSetName = "Data_Root";
oDS.Namespace = strFilePath;
oDS.Tables.Add("Table1");
StreamReader oSR = new StreamReader(strFilePath);
//Go to the top of the file
oSR.BaseStream.Seek(0, SeekOrigin.Begin);
//Add in the Header Columns
foreach (string strFields1 in oSR.ReadLine().Split(strDelimiter))
oDS.Tables[0].Columns.Add(strFields1);
//Now add in the Rows
oTable = oDS.Tables[0];
while (oSR.Peek() > -1)
{
oRows = oTable.NewRow();
foreach (string strFields2 in oSR.ReadLine().Split(strDelimiter))
{
oRows[intCounter] = strFields2;
intCounter = intCounter + 1;
}
intCounter = 0;
oTable.Rows.Add(oRows);
}
//Create XML file
oDS.WriteXml("c:/Text_To_XML.xml");
}