Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 131,940 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,893 people online right now. Registration is fast and FREE... Join Now!





Convert delimited file to XML

This is a small snippet showing how to convert a delimited file to an XML document

Submitted By: PsychoCoder
Actions:
Rating:
Views: 1,054

Language: C#

Last Modified: September 1, 2007
Instructions: This method requires 3 parameters:

delimiter: The delimiter the file is delimited with
file: The name of the file
xmlFileName: name and path of the XML file you wish to create

Snippet


  1. public void ConvertDelimitedToXML(char delimiter, string file,string xmlFileName)
  2. {
  3.     //create the objects we need
  4.     System.Data.DataSet xmlDataSet = new System.Data.DataSet();
  5.     System.Data.DataTable xmlTable = new System.Data.DataTable();
  6.     System.Data.DataRow xmlRows;
  7.  
  8.     using (StreamReader reader = new StreamReader(file))
  9.     {
  10.         //set the DataSetName of the DataSet
  11.         xmlDataSet.DataSetName = "YourName";
  12.         //set the NameSpace of the DataSet
  13.         xmlDataSet.Namespace = "YourNamespace";
  14.  
  15.         //make sure we're at the beginning of the file
  16.         reader.BaseStream.Seek(0, SeekOrigin.Begin);
  17.         //add the header columns
  18.         foreach (string fields in reader.ReadLine().Split(delimiter))
  19.         {
  20.              //xmlDataSet.Tables(0).Columns.Add(fields);
  21.              xmlTable.Columns.Add(fields);
  22.         }
  23.         //now add the rows
  24.         while (reader.Peek() != -1)
  25.         {
  26.             xmlRows = xmlTable.NewRow();
  27.             foreach (string fields in reader.ReadLine().Split(delimiter))
  28.             {
  29.                  xmlTable.Rows.Add(fields);
  30.             }
  31.             //add the new rows to the table
  32.                     xmlTable.Rows.Add(xmlRows);
  33.         }
  34.         //add the table to the DataSet
  35.         xmlDataSet.Tables.Add(xmlTable);
  36.         //write out the XML
  37.         xmlDataSet.WriteXml(xmlFileName);
  38.     }           
  39. }

Copy & Paste


Comments


johnsvakel 2007-12-10 20:29:33

Hi thanks a lot,its very helful for me.


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month