【问题标题】:linq to create xml from csvlinq 从 csv 创建 xml
【发布时间】:2010-07-04 04:38:44
【问题描述】:

我看到了这篇很棒的帖子: http://sqldud.blogspot.com/2009/01/how-to-convert-csv-to-xml-using-c.html

我有一个 csv 文件,其中列标题位于 csv 的第一行。 我还希望 linq 语句能够处理可变长度的列数。 这样,如果添加更多列,我就不必更改代码。 有没有办法做到这一点? 如果元素是列标题(第一行)的名称,那就太好了。

【问题讨论】:

    标签: xml linq


    【解决方案1】:

    您可以使用如下代码完成此操作

    string inputFile = @"C:\Temp\somefile.csv";
    string outputFile = @"C:\Temp\somefile_output.xml";
    
    XDocument document = new XDocument();
    document.Add(new XElement("root"));
    
    using (StreamReader reader = new StreamReader(inputFile))
    {
        string[] headerRow = reader.ReadLine().Split(',');
        while (!reader.EndOfStream)
        {
            string[] items = reader.ReadLine().Split(',');
    
            document.Root.Add(new XElement("row",
                from item in items.Select((val, idx) => new { val, idx })
                join header in headerRow.Select((val, idx) => new { val, idx })
                on item.idx equals header.idx
                select new XElement(header.val, item.val)));
        }
    }
    
    document.Save(outputFile);
    

    这会变成一个包含以下内容的 CSV 文件

    FirstField,SecondField,ThirdField,FourthField
    1,2,3,4
    5,6,7,8
    9,10,11,12
    13,14,15,16
    

    写入 XML 文档

    <?xml version="1.0" encoding="utf-8"?>
    <root>
      <row>
        <FirstField>1</FirstField>
        <SecondField>2</SecondField>
        <ThirdField>3</ThirdField>
        <FourthField>4</FourthField>
      </row>
      <row>
        <FirstField>5</FirstField>
        <SecondField>6</SecondField>
        <ThirdField>7</ThirdField>
        <FourthField>8</FourthField>
      </row>
      <row>
        <FirstField>9</FirstField>
        <SecondField>10</SecondField>
        <ThirdField>11</ThirdField>
        <FourthField>12</FourthField>
      </row>
      <row>
        <FirstField>13</FirstField>
        <SecondField>14</SecondField>
        <ThirdField>15</ThirdField>
        <FourthField>16</FourthField>
      </row>
    </root>
    

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多