我看到了这篇优秀的帖子: http://sqldud.blogspot.com/2009/01/how-to-convert-csv-to-xml-using-c.html
我有一个csv文件,其中列标题位于csv的第一行。 我还希望linq语句能够处理可变长度的列数。 这样,如果添加更多列,我就不必更改代码。 有没有办法做到这一点? 如果元素是列标题的名称(第一行),那将是很好的。
答案 0 :(得分: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>