简体   繁体   English

使用 C# 在 XML 文件中转换 CSV

[英]Convert CSV in XML file with C#

I wrote this piece of code that allows me to read a CSV file and convert it to an XML file.我编写了这段代码,它允许我读取 CSV 文件并将其转换为 XML 文件。 I have a problem, if inside the CSV file there are semicolons (;) the program cannot read the data instead, if there are commas (,) that delimit the words the program can read the data and to insert them correctly in the XML file.我有一个问题,如果在 CSV 文件中有分号 (;),程序将无法读取数据,如果有逗号 (,) 分隔程序可以读取数据的单词并将它们正确插入到 XML 文件中. could you find a way to replace the semicolon (;) with the comma (,)?你能找到一种用逗号 (,) 替换分号 (;) 的方法吗? Thank you very much!!非常感谢!! :) :)

This is the code:这是代码:

        writer.WriteStartDocument();
        writer.WriteStartElement("DC8_Recipes");

        using (CsvReader reader = new CsvReader(path))
        {
            reader.ReadHeaders();

            while (reader.ReadRecord())
            {
                writer.WriteStartElement("DC8_Recipes");

                writer.WriteAttributeString("PlantNo", reader["id_imp"]);
                writer.WriteAttributeString("No", reader["nome_frm"]);
                writer.WriteAttributeString("Name", reader["desc_frm"]);

                writer.WriteEndElement();
            }
            reader.Close();
        }

        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Close();


        logText.Text += DateTime.Now + " Convertion Completed\n";
        logText.Text += DateTime.Now + " Saving file to: " + savepath + "\n";
        try
        {
            logText.Text += DateTime.Now + " File save completed!\n";
            logText.Text += DateTime.Now + " process END\n";
        }
        catch
        {

        }
    }

You can pass into CsvReader constructor a CsvConfiguration to change the default delimiter ( which is based on the current CultureInfo ):您可以向CsvReader构造函数传递一个CsvConfiguration以更改默认分隔符(基于当前 CultureInfo ):

The culture is used to determine the default delimiter, default line ending, and formatting when type converting.区域性用于确定类型转换时的默认分隔符、默认行尾和格式。

using (var csv = new CsvReader(writer, new CsvConfiguration(CultureInfo.InvariantCulture) 
{ 
    Delimiter = "," 
}))
{
    csv.Read();
}

You could write your own CsvReader :您可以编写自己的CsvReader

    public static List<Model> ReadCsv(string path)
    {
        var modelList = new List<Model>();
        using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            using (var streamReader = new StreamReader(fileStream, Encoding.Default))
            {
                while (!streamReader.EndOfStream)
                {
                    var line = streamReader.ReadLine();

                    if (string.IsNullOrEmpty(line))
                    {
                        continue;
                    }

                    var splittedLine = line.Split(';');

                    var model = new Model();

                    for (var i = 0; i < splittedLine.Length; i++)
                    {
                        switch (i)
                        {
                            case 0:
                                model.FirstColumn = splittedLine[i];
                                break;
                            case 1:
                                model.SecondColumn = splittedLine[i];
                                break;
                            case 2:
                                model.ThirdColumn = Convert.ToInt32(splittedLine[i]);
                                break;
                        }
                    }

                    modelList.Add(model);
                }
            }
        }

        return modelList;
    }

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

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