2

我想读取一个 CSV 文件并从中写入一个 XML 文件。我了解如何拆分 csv 行的基本思想。但是我的代码给了我一个例外,我不明白。

首先是代码:

    static void Main(string[] args)
    {
       Console.WriteLine("Insert Filename please");
       string path = Console.ReadLine();

           string[] source = File.ReadAllLines(path);
           XElement output = new XElement("Consumer",
               from str in source
               let fields = str.Split(',')
               select new XElement("consumer",
                   new XElement(fields[0],
                   new XAttribute(fields[1], fields[2]),
                   new XAttribute(fields[3], fields[4])
                   )));

                Console.WriteLine(output);
                Console.ReadLine();
    }

}

这就是代码,当我调试它时,我收到一条失败消息,上面写着“OutOfRangeException”。我知道这种异常意味着什么,但我就是找不到解决方案。我将逗号之间的每个字符都解释为一个字段。因此,通常数组不应大于 CSV 文件中的字段数量。为什么我现在得到 OutOfBounds,对我来说很神秘。

非常感谢您的阅读和帮助:)

编辑:我使用的 CSV 文件已损坏,因此我没有得到任何有用的东西。我已修复并且代码有效,但只要 CSV 不包含空字段。弹出的异常是,“名称不能以字符''开头,十六进制值 0x20。我不知道如何处理这个问题。我尝试使用 Lumenworks 的 FastCSVReader 库,但没有得到解决方案。

4

1 回答 1

2

必须至少有一行少于 37 个字段。也许最后有一个空行?

fields.Length您可以在继续之前尝试检查,即:

XElement toXML = new XElement("Root",
from str in source
let fields = str.Split(',')
where fields.Length >= 37 // <==== Check #fields
select new XElement("Consumer",
            new XAttribute("name", fields[0]),
        new XElement(fields[3]),
            new XAttribute(fields[4], fields[5]),
            new XAttribute(fields[6], fields[7]),
            new XAttribute(fields[8], fields[9]),
            new XAttribute(fields[10], fields[11]),
            new XAttribute(fields[12], fields[13]),
            new XAttribute(fields[14], fields[15]),
            new XAttribute(fields[16], fields[17]),
            new XAttribute(fields[18], fields[19]),
            new XAttribute(fields[20], fields[21]),
        new XElement(fields[22]),
              new XAttribute(fields[24], fields[25]),
              new XAttribute(fields[26], fields[27]),
              new XAttribute(fields[28], fields[29]),
        new XElement(fields[30]),
              new XAttribute(fields[32], ""),
              new XAttribute(fields[33], fields[34]),
              new XAttribute(fields[35], fields[36])));
于 2013-07-05T12:40:47.037 回答