0

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]); 
},

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Laïla B
  • 11
  • 3

2 Answers2

0

Instead of using a loop, you can just use Linq:

  XElement element = new XElement("DOCUMENT",
    new XElement("GED",
      from li in source
      let champs = ligne.Split(';')
      select new XElement("INDEX", champs.Select(c => new XElement(c, c)))
    )
  );
Lennart Stoop
  • 1,649
  • 1
  • 12
  • 18
0

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

Jack J Jun
  • 5,633
  • 1
  • 9
  • 27