【发布时间】:2023-04-08 09:53:01
【问题描述】:
我正在尝试根据 Microsoft 的本教程将多个 CSV 文件多次转换为 XML:
// Create the text file.
string csvString = @"GREAL,Great Lakes Food Market,Howard Snyder,Marketing Manager,(503) 555-7555,2732 Baker Blvd.,Eugene,OR,97403,USA
HUNGC,Hungry Coyote Import Store,Yoshi Latimer,Sales Representative,(503) 555-6874,City Center Plaza 516 Main St.,Elgin,OR,97827,USA
LAZYK,Lazy K Kountry Store,John Steel,Marketing Manager,(509) 555-7969,12 Orchestra Terrace,Walla Walla,WA,99362,USA
LETSS,Let's Stop N Shop,Jaime Yorres,Owner,(415) 555-5938,87 Polk St. Suite 5,San Francisco,CA,94117,USA";
File.WriteAllText("cust.csv", csvString);
// Read into an array of strings.
string[] source = File.ReadAllLines("cust.csv");
XElement cust = new XElement("Root",
from str in source
let fields = str.Split(',')
select new XElement("Customer",
new XAttribute("CustomerID", fields[0]),
new XElement("CompanyName", fields[1]),
new XElement("ContactName", fields[2]),
new XElement("ContactTitle", fields[3]),
new XElement("Phone", fields[4]),
new XElement("FullAddress",
new XElement("Address", fields[5]),
new XElement("City", fields[6]),
new XElement("Region", fields[7]),
new XElement("PostalCode", fields[8]),
new XElement("Country", fields[9])
)
)
);
Console.WriteLine(cust);
我正计划使用 foreach 循环来遍历目录中需要转换的所有 CSV 文件,尽管我遇到了麻烦。
行内:
string[] source = File.ReadAllLines("cust.csv");
是否有一种方法可以将 cust.csv 替换为通配符运算符 (*.csv),以便它获取它运行的所有 CSV 文件,例如:
string[] source = File.ReadAllLines("*.csv");
我知道上面的方法不起作用,因为 ReadAllLines 不支持“*”,但是这样做的逻辑是什么,以便循环遍历所有 CSV 文件,然后将逻辑转换应用于它们?
【问题讨论】:
-
"但是这样做的逻辑是什么,以便循环遍历所有 CSV 文件,然后将逻辑转换应用于它们?" -> 获取所有文件名给定以“.csv”结尾的目录,然后遍历它们。
-
str.Split(',')不是 csv 解析器。 “正确”的 csv 文件可能包含引用的值。
标签: c# xml csv file-conversion