Wednesday, September 23, 2009

CSV to XML Conversion using LINQ

on C#, if we want to Convert CSV to XML then you can use 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

below example 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 ConvCSVToXML()

{

String[] FileContent = File.ReadAllLines(@"D:\Proj\jquery.csv");

String XMLNS = "";

XElement Inv = new XElement("type", from

items in FileContent

let fields = items.Split(',')

select new XElement("fadein",

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

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

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

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

)
);

File.WriteAllText(@"D:\Proj\jquery.xml", XMLNS + Inv.ToString() );
}


using this you can convert your CSV file xml using C# and C# Convert CSV To XML, .NET CSV To XML

3 comments:

  1. Hi there,

    What if you have more than 100 item in the cvs file, it is gona be a lot work to write 100 statment for each item, is there a better (dynamic) way to loop the entries !!

    Thanks,
    Waleed

    ReplyDelete
  2. can you tell me how to convert xml to pdf? I have been wondering if there is a way to do that with a program, or with something that is free.

    ReplyDelete
  3. Anonymous said it wright what if is as many items u cannot go by this so any one has coding for dynamically getting csv to xml

    ReplyDelete