I would like to be able to Read from a CSV file that will have "fields", lets call them ID, Name, Price. I want to be able to create a seperate XML file for each row in the CSV file. Right now, i have it so it will read all the lines in the csv file and make one big xml. The CSV file contains this:
2, Banana,33,45

The xml file it creates looks like this:
<Name> Banana</Name>

using System;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace CsvToXml
    class Program
        static void Main(string[] args)

            String[] FileContent = File.ReadAllLines(@"C:\Users\Zach\Desktop\test.csv");
            String XMLNS = "";

            XElement Inv = new XElement("Invoice",
                new XElement("Store",
                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])

            File.WriteAllText(@"C:\Users\Zach\Desktop\text.xml", XMLNS + Inv.ToString());


Any help would be appreciated!! thanks!

4 Years
Discussion Span
Last Post by nmaillet

You could use a loop. First, if your CSV files get very big, this is going to consume a large chunk of memory to store the entire file at once. I would recommend using a StreamReader with the ReadLine() method in a loop. You can start with something like this:

using(StreamReader reader = new StreamReader(@"C:\Users\Zach\Desktop\test.csv"))
    for(string line = reader.ReadLine(); line != null; line = reader.ReadLine())

Once the StreamReader is disposed of, the file will be closed. Now, back to your question. Each iteration of the loop, you'll want to construct an XElement and parse the single line of the CSV file. You can then store it to a file, either by using your method or using the XElement.Save() method. Using the Save() method adds the <?xml ... ?> tag to the beginning of the file. This makes it a valid XML file, but could consume more disk space.


Ok that makes sense. Now my question is...for the "line", how do i split the line into parts? Meaning..each variable, split by the comma, i need to write that to each element?


You would just use the string.Split() method. Essentially the same thing you did in the LINQ statement.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.