Just Code‎ > ‎

C# - Convert any CSV file to XML file

posted Jul 4, 2012, 8:01 AM by Peter Henell   [ updated Jul 4, 2012, 8:03 AM ]
It is bold to say ANY, but this will work for most :) It is assuming first row is headers and that the headers and regular fields are separated using the same character
public static void Csv2Xml(string sourceFileName, string targetFileName, char fieldSplitCharacter)
        {
            if (!string.IsNullOrEmpty(sourceFileName))
            {
                if (File.Exists(sourceFileName))
                {
                    string[] lines = File.ReadAllLines(sourceFileName);
                    string[] headers = lines[0].Split(fieldSplitCharacter);
                    var data = lines.Skip(1);
                    XmlWriter writer = XmlWriter.Create(targetFileName);
                    writer.WriteStartElement("ROOT");

                    foreach (var d in data)
                    {
                        writer.WriteStartElement("row");
                        for (int i = 0; i < headers.Length; i++)
                        {
                            string[] cols = d.Split(fieldSplitCharacter);
                            writer.WriteAttributeString(headers[i], cols[i]);
                        }
                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                }
                //MessageBox.Show("done");
            }
        }
Comments