简体   繁体   English

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

[英]how to convert csv file to xml file in c# by columns

right now I have csv file in there it contains Worker, Account Id, Account Code, Hierarchy, and Date column. 现在,我在其中有一个csv文件,其中包含工作程序,帐户ID,帐户代码,层次结构和日期列。 how do I write c# code to convert csv file to xml file? 如何编写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]),

For now I have code something like that, how can I make improve on that code? 现在,我有类似的代码,如何对该代码进行改进?

Perhaps you could ensure the column names are the same by doing something like: 也许可以通过执行以下操作来确保列名相同:

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

That way you wouldn't have to continually type in every single column name, and could just use a foreach(..) block to generate it instead. 这样,您将不必连续输入每个列名,而只需使用foreach(..)块来生成它即可。

Try this 尝试这个

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

Well there's a class from MSDN called XmlCsvReader You only have to specify your filepath where the csv document is located. 好吧, MSDN中有一个名为XmlCsvReader的类,您只需指定csv文档所在的文件路径即可。 Then you specify your root's name which is Worker and it'll take care of the rest when it's loaded. 然后,您指定根的名称为Worker,并且在加载时将处理其余部分。 The only thing that needs to be done is to specify where you want to output it using the Save method! 唯一需要做的就是使用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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM