【问题标题】:Use a "for" loop in XElement在 XElement 中使用“for”循环
【发布时间】:2019-10-31 10:31:46
【问题描述】:

我正在尝试创建一个转换器 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]); 
},

【问题讨论】:

    标签: c# loops xelement


    【解决方案1】:

    您可以尝试以下代码将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 文件:

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 如何输入“col[i]”值?
      • col[i] 在哪里声明?它的价值从何而来?
      • col[i] 来自我的 csv 文档的第一行(例如“title”),我希望它是 xml 中的 ,例如 newElement(col[i ] , 冠军[i])
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多