Search code examples
c#loopsxelement

Use a "for" loop in XElement


I'm trying to create a converter CSV to XML. The XML files might not have always the same number of fields, so i'm trying to get this number and then use it to create the elements

string[] source = new string[] { ligne };  
                    XElement element = new XElement("DOCUMENT",
                        new XElement("GED",
                            from li in source  
                            let champs = ligne.Split(';')
                            select new XElement("INDEX",
                           // where i'd like to put the loop code
                            new XElement(col[0], champs[0]),
                            new XElement(col[1], champs[1]),
                            new XElement(col[2], champs[2])... //etc,
                            )
                        )
                    );
//the code i'd like to put in the previous code
for (int i = 0; i < col.Length +1; i ++)
{
     new XElement(col[i], champs[i]); 
},


Solution

  • You can try the following code to convert the csv file to the xml file you want.

    var lines = File.ReadAllLines(@"D:\t\Book1.csv");
    
    string[] headers = lines[0].Split(',').Select(x => x.Trim('\"')).ToArray();
    
    var xml = new XElement("TopElement",
              lines.Where((line, index) => index > 0).Select(line => new XElement("Item",
              line.Split(',').Select((column, index) => new XElement(headers[index], column)))));
    
    xml.Save(@"d:\xmlout.xml");
    

    CSV file:

    enter image description here

    Xml file:

    enter image description here