Tuesday, 28 January 2014

Converting CSV to XML and then to C# Object List

Recently I was working on a project where I had to convert a CSV file to XML.
CSV was generated from a database table. Later that XML has to be converted to C# list and used in the project as setting values.

I'll use a sample csv data here that contains information about few students like their roll number, name and marks in various subjects

Create a C# Console application and add csv file in Resources folder. I'm naming it StudentMarks.csv.



Open Properties of StudentMarks.csv by right clicking on it. Then change value of Copy to Output Directory to Copy Always.
Then we will create a Student Class
Now in the MainProgram.cs create a method to convert CSV to XML. It accepts two paramters one for input csvFilePath and other for output xmlFilePath

First we are reading all the lines of csv file as list of strings. Then we will extract the header values from first line which will be used as xml attributes for data values. After that we will convert rest of the lines into XElement object and use the extracted header values to create xml attributes.
The Resulting XML will look like following


Now add one more method to convert from XML to C# list. This method accepts filepath of XML file and returns List of Students Object.
Here we will use XDocument class to load XML values and then Linq query to get the list.

Now from the Main Method call above created methods with proper parameter values.
That’s it. I've shared the solution folder at https://github.com/kushdilip/CSharp_Experiments/.

 For any doubts please comment.
 

No comments:

Post a Comment