Chat LIVE With Programming Experts! There Are 23 Online Right Now...

 

Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Become a C# Expert!

Join 244,258 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,274 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: 2,431

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!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month