将 CSV 文件转换为 XML
我需要将 CSV 转换为 XML 文档。到目前为止我看到的示例都展示了如何使用 CSV 中固定数量的列来执行此操作。
到目前为止,我使用 LINQ:
String[] File = File.ReadAllLines(@"C:\text.csv");
String xml = "";
XElement top = new XElement("TopElement",
from items in File
let fields = items.Split(';')
select new XElement("Item",
new XElement("Column1", fields[0]),
new XElement("Column2", fields[1]),
new XElement("Column3", fields[2]),
new XElement("Column4", fields[3]),
new XElement("Column5", fields[4])
)
);
File.WriteAllText(@"C:\xmlout.xml", xml + top.ToString());
这是针对固定数量的列,但我的 .CSV 每行都有不同数量的列。
您将如何根据 .CSV 的每一行中有多少个单词(列)来适应某种循环?
谢谢
I need to Convert a CSV into an XML document. The examples I have seen so far, all show how to do this with a fixed number of columns in the CSV.
I have this so far, using LINQ:
String[] File = File.ReadAllLines(@"C:\text.csv");
String xml = "";
XElement top = new XElement("TopElement",
from items in File
let fields = items.Split(';')
select new XElement("Item",
new XElement("Column1", fields[0]),
new XElement("Column2", fields[1]),
new XElement("Column3", fields[2]),
new XElement("Column4", fields[3]),
new XElement("Column5", fields[4])
)
);
File.WriteAllText(@"C:\xmlout.xml", xml + top.ToString());
This is for a fixed amount of columns, but my .CSV has a different number of columns on each line.
How would you fit some sort of loop into this, depending on how many words (columns) there are in each line of the .CSV?
Thnx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
输入:
输出:
Input:
Output:
如果您想使用标题作为元素名称:
In case you want use the headers as the elements names:
我编写了一个源自 Vlax 代码片段的类。
此外,我还提供了一个单元测试来记录工作流程。
单元测试:
CSV 到 XML:
注意:
我通过删除导致运行时的每个 CSV 行条目的尾随逗号来扩展 Vlax 的解决方案基于索引相对于列标题越界的异常。
I wrote a class that derives from Vlax's snippet.
In addition I have provided a unit test to document the workflow.
Unit Test:
CSV to XML:
NOTE:
I extended Vlax's solution by removing a trailing comma for each of the CSV line entries that caused a runtime exception based on an index being out of bounds in relation to the column header.
这里提供了一种不使用嵌套LINQ的解决方案,更容易理解。
input.csv
的内容:处理代码:
Program.cs
运行代码后,结果如下:
可以在此处查看此代码的完整 Visual Studio 解决方案:
https://github.com/yanglr/dotnetInterview/tree/master/CSVtoXML。
Here provides a solution without using nested LINQ, simpler to understand.
The content of
input.csv
:The code for process:
Program.cs
After running the code, the result is below:
The complete visual studio solution for this code can be seen here:
https://github.com/yanglr/dotnetInterview/tree/master/CSVtoXML.
Cinchoo ETL - 一个开源库,可轻松将 CSV 转换为 Xml代码行
对于示例 CSV:
输出 Xml:
查看 CodeProject 文章了解一些额外的帮助。
免责声明:我是这个库的作者。
Cinchoo ETL - an open source library available to do the conversion of CSV to Xml easily with few lines of code
For a sample CSV:
Output Xml:
Checkout CodeProject article for some additional help.
Disclaimer: I'm the author of this library.