Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
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])
    )
);
 
xml.Save(@"C:\XMLFile.xml");
 
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
 
<Root>
<Employee>
 
<ID>1</ID>
<Name>John Walker</Name>
<Title>HR Manager</Title>
<City>San Francisco</City>
<Region>CA</Region>
<Country>USA</Country>
</Employee>
<Employee>
<ID>2</ID>
<Name>Caroline Anderson</Name>
<Title>Marketing Manager</Title>
<City>Cincinnati</City>
<Region>OH</Region>
<Country>USA</Country>
</Employee>
<Employee>
<ID>3</ID>
<Name>George Clevard</Name>
<Title>CTO</Title>
<City>Seattle</City>
<Region>WA</Region>
<Country>USA</Country>
</Employee>
<Employee>
<ID>4</ID>
<Name>James Carell</Name>
<Title>CFO</Title>
<City>Houston</City>
<Region>TX</Region>
<Country>USA</Country>
</Employee>
<Employee>
<ID>5</ID>
<Name>Tom Nicholson</Name>
<Title>CEO</Title>
<City>Tallahassee</City>
<Region>FL</Region>
<Country>USA</Country>
</Employee>
</Root>
 

 

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

Disclaimer - Privacy
© 2002-2017 DevASP.net