Convert CSV file to XML
        Posted  
        
            by Soeren
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Soeren
        
        
        
        Published on 2010-06-18T12:45:35Z
        Indexed on 
            2010/06/18
            12:53 UTC
        
        
        Read the original article
        Hit count: 380
        
I need to Convert a CSV into an XML document. The examples I have seen so far, all show how to do this with a fixed number of columns in the CSV.
I have this so far, using LINQ:
String[] File = File.ReadAllLines(@"C:\text.csv");
        String xml = "";
        XElement top = new XElement("TopElement",
        from items in File
        let fields = items.Split(';')
        select new XElement("Item",
        new XElement("Column1", fields[0]),
        new XElement("Column2", fields[1]),
        new XElement("Column3", fields[2]),
        new XElement("Column4", fields[3]),
        new XElement("Column5", fields[4])
        )
        );
        File.WriteAllText(@"C:\xmlout.xml", xml + top.ToString());
This is for a fixed amount of columns, but my .CSV has a different number of columns on each line.
How would you fit some sort of loop into this, depending on how many words (columns) there are in each line of the .CSV?
Thnx
© Stack Overflow or respective owner