C# 如何在c中按列将csv文件转换为xml文件
现在我有csv文件在那里,它包含工人,帐户Id,帐户代码,层次结构和日期列。如何编写c代码将csv文件转换为xml文件C# 如何在c中按列将csv文件转换为xml文件,c#,xml,csv,C#,Xml,Csv,现在我有csv文件在那里,它包含工人,帐户Id,帐户代码,层次结构和日期列。如何编写c代码将csv文件转换为xml文件 select new XElement("Worker", new XElement("Account Id", columns[0]), new XElement("Account Code", columns[1]), new XElement("Hierarchy", columns[2]), new XElement("Date", co
select new XElement("Worker",
new XElement("Account Id", columns[0]),
new XElement("Account Code", columns[1]),
new XElement("Hierarchy", columns[2]),
new XElement("Date", columns[3]),
现在我有了这样的代码,如何改进代码?也许您可以通过执行以下操作来确保列名相同:
new XElement(columns[0].Key, columns[0].value)
这样,您就不必连续输入每个列名,只需使用foreach。。块来生成它。有一个名为XmlCsvReader的类,您只需指定csv文档所在的文件路径。然后指定根目录的名称,即Worker,在加载它时,它将处理其余部分。唯一需要做的事情是使用Save方法指定输出它的位置
XmlDocument doc = new XmlDocument();
XmlCsvReader reader = new XmlCsvReader(new Uri("//yourfilepath.input.csv"), doc.NameTable);
reader.FirstRowHasColumnNames = true;
reader.RootName = "Worker";
reader.RowName = "Worker";
doc.Load(reader);
doc.Save("output.xml");
试试这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.IO;
namespace ConsoleApplication55
{
class Program
{
const string csvFILENAME = @"c:\temp\test.csv";
const string xmlFILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
CSVReader reader = new CSVReader();
DataSet ds = reader.ReadCSVFile(csvFILENAME, true);
ds.WriteXml(xmlFILENAME, XmlWriteMode.WriteSchema);
}
}
public class CSVReader
{
public DataSet ReadCSVFile(string fullPath, bool headerRow)
{
string path = fullPath.Substring(0, fullPath.LastIndexOf("\\") + 1);
string filename = fullPath.Substring(fullPath.LastIndexOf("\\") + 1);
DataSet ds = new DataSet();
try
{
if (File.Exists(fullPath))
{
string ConStr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}" + ";Extended Properties=\"Text;HDR={1};FMT=Delimited\\\"", path, headerRow ? "Yes" : "No");
string SQL = string.Format("SELECT * FROM {0}", filename);
OleDbDataAdapter adapter = new OleDbDataAdapter(SQL, ConStr);
adapter.Fill(ds, "TextFile");
ds.Tables[0].TableName = "Table1";
}
foreach (DataColumn col in ds.Tables["Table1"].Columns)
{
col.ColumnName = col.ColumnName.Replace(" ", "_");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return ds;
}
}
}
那对你不起作用?