I saw this excellent post: http://sqldud.blogspot.com/2009/01/how-to-convert-csv-to-xml-using-c.html
I have a csv f开发者_如何学JAVAile with the column titles in the first row of the csv. I would also like the linq statement to be able to handle a variable length number of columns. That way I would not have to change the code if more columns are added. Is there a way to do this? It would be great if the elements were the name of the column headers(first row).
You could accomplish this with code like the following
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);
Which would turn a CSV file with the following contents
FirstField,SecondField,ThirdField,FourthField
1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16
Into an XML document
<?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>
精彩评论