Windows Phone Developers

Saturday, October 18, 2008

C# CSV to XML Conversion, CSV to XML Conversion using LINQ

How to Convert CSV to XML using C#

Language Integrated Query (LINQ) can be used to convert a CSV file to XML. Here is the sample CSV file that needs to be converted

The following code reads the CSV file to an array. LINQ is used to loop through the array and the contents are written as XML using XElement (System.XML.Linq).

public void ConvertCSVToXML()


String[] FileContent = File.ReadAllLines(@"C:\Temp\vba.csv");

String XMLNS = "";

XElement Inv = new XElement("Invoice",

from items in FileContent

let fields = items.Split(',')

select new XElement("Item",

new XElement("ID", fields[0]),

new XElement("Name", fields[1]),

new XElement("Price", fields[2]),

new XElement("Availability", fields[3]),

new XElement("TotalPrice", fields[4])



File.WriteAllText(@"C:\Temp\vba.xml", XMLNS + Inv.ToString() );


Here is the Input Text File

The output XML looks like

LINQ and C#, C# Convert CSV To XML, .NET CSV To XML, LINQ CSV to XML, Convert Text files to XML using C#, Create XML files from CSV (Text) files using .NET (C#), C Sharp Convert Text File (CSV) to XML file

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon


  1. How about the conversion without LINQ..i am having VS 2005 so i guess i can not use LINQ??

  2. how does the array know how many fields it has?
    so the array string dosnt define how many fields it has?

    I add more fields but i dont know how to tell the array that there are more fields.

    Index was outside the bounds of the array.

    1. use ARRAY.Resize(ref array_name,and_new_size);

  3. how about creating a new xml file while converting?