Hello,

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:
1,Apple,23,44
2, Banana,33,45
3,Pie,111,66

The xml file it creates looks like this:
"
<Invoice>
<Store>
<Item>
<ID>1</ID>
<Name>Apple</Name>
<Price>23</Price>
</Item>
<Item>
<ID>2</ID>
<Name> Banana</Name>
<Price>33</Price>
</Item>
<Item>
<ID>3</ID>
<Name>Pie</Name>
<Price>111</Price>
</Item>
</Store>
</Invoice>
"

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!

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 article has been dead for over six months. Start a new discussion instead.