在 XElement 中使用 "for" 循环

Use a "for" loop in XElement

我正在尝试创建一个 CSV 格式的转换器以 XML。 XML 文件可能不总是有相同数量的字段,所以我试图获取这个数字,然后用它来创建元素

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

您可以只使用 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)))
    )
  );

您可以尝试以下代码将csv文件转换成您想要的xml文件。

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 文件:

Xml 文件: