如何将csv文件转换为c#中的xml文件

时间:2015-11-02 23:41:48

标签: c# xml csv

现在我有csv文件,其中包含Worker,Account Id,Account Code,Hierarchy和Date列。如何编写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", columns[3]),

现在我有类似的代码,如何改进代码呢?

3 个答案:

答案 0 :(得分:1)

也许您可以通过执行以下操作来确保列名相同:

new XElement(columns[0].Key, columns[0].value)

这样你就不必连续输入每一个列名,而只需使用foreach(..)块来生成它。

答案 1 :(得分:1)

试试这个

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;
        }
    }
}

答案 2 :(得分:0)

那么来自MSDN的一个名为XmlCsvReader的类您只需要指定csv文档所在的文件路径。然后你指定你的根名称是工人,并在它加载时处理其余部分。唯一需要做的就是使用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");