Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
SQL Server

How to generate XML from CSV file in C#

Author: Mike Green

We will see how we can generate XML file from CSV file in C# using LINQ.

Sometimes, in our application, we receive information in a CSV file and we need to convert this data into XML format. There are number of solutions available to achieve this task and you can also use third party code samples in your application. LINQ is a convenient and easy way to solve this problem that is why I am using LINQ in my code. There are number of articles available on DevASP.NET about LINQ. You can learn how to do different things using LINQ by reading these articles. Following piece of code will describe how simply we can generate a XML file from a CSV file using LINQ in C#.

using System.IO;
using System.Xml.Linq;
string[] lines = File.ReadAllLines(@"C:\CSVFile.csv");
XElement xml = new XElement("Root",
    from str in lines
    let columns = str.Split(',')
    select new XElement("Employee",
        new XElement("ID", columns[0]),
        new XElement("Name", columns[1]),
        new XElement("Title", columns[2]),
        new XElement("City", columns[3]),
        new XElement("Region", columns[4]),
        new XElement("Country", columns[5])
CSV file has following data
1,John Walker,HR Manager,San Francisco,CA,USA
2,Caroline Anderson,Marketing Manager,Cincinnati,OH,USA
3,George Clevard,CTO,Seattle,WA,USA
4,James Carell,CFO,Houston,TX,USA
5,Tom Nicholson,CEO,Tallahassee,FL,USA
Here is the output in XML format
<Name>John Walker</Name>
<Title>HR Manager</Title>
<City>San Francisco</City>
<Name>Caroline Anderson</Name>
<Title>Marketing Manager</Title>
<Name>George Clevard</Name>
<Name>James Carell</Name>
<Name>Tom Nicholson</Name>


Add Article Comment:
Name :
Email Address :
Comments :
<< How to generate CAPTCHA in C#

Disclaimer - Privacy
© 2002-2017