C# CSV分隔为XML-文件夹层次结构

C# CSV分隔为XML-文件夹层次结构,c#,xml,linq,csv,doubly-linked-list,C#,Xml,Linq,Csv,Doubly Linked List,这是我第一次发帖,所以我为我对示例的无知或使用失败表示歉意 我有一个控制台应用程序项目要创建,在那里我得到了相当多的CSV文件,我需要从中创建某种父/子/孙关系(XML?也许?-然后我可以用它进行上传和写入DMS,只需很少的调用-我不想反复查询文件夹是否存在) 在这件事上我有点不知所措 我需要知道没有第三方库依赖的最佳方法,纯C#,最有可能需要使用OLEDB JET提供程序,因为它将处理所需的解析,CSV文件没有顺序,以前的年份可能会出现在列表中,反之亦然 下面是CSV输出的一个示例 "DESC

这是我第一次发帖,所以我为我对示例的无知或使用失败表示歉意

我有一个控制台应用程序项目要创建,在那里我得到了相当多的CSV文件,我需要从中创建某种父/子/孙关系(XML?也许?-然后我可以用它进行上传和写入DMS,只需很少的调用-我不想反复查询文件夹是否存在)

在这件事上我有点不知所措

我需要知道没有第三方库依赖的最佳方法,纯C#,最有可能需要使用OLEDB JET提供程序,因为它将处理所需的解析,CSV文件没有顺序,以前的年份可能会出现在列表中,反之亦然

下面是CSV输出的一个示例

"DESCRIPTION1","8, 5/8\" X 6.4MM","STRING","filename001.pdf","2016-09-19","1"  
"DESCRIPTION2","12, 3/4\" X 6.4MM","STRING","filename001.pdf","2016-09-19","1"  
"DESCRIPTION3","12, 3/4\" X 6.4MM","STRING","filename001.pdf","2016-09-19","1"  
"another description 20# gw","1","388015","Scan123.pdf","2015-10-24","1"  
"another description 20# gw","3","385902","Scan456.pdf","2015-04-14","1"  
"STRINGVAL1","273.10 X 9.27 X 6000","45032-01","KHJDWNEJWKFD9101529.pdf","2012-02-03","1"  
"STRINGVAL2","273.10 X 21.44 X 6000","7-09372","DJSWH68767681540.pdf","2017-02-03","1"  
最终输出为(
YEAR/MONTH/FILENAME
+(每个文件的属性-这些属性用于最终更新DMS中的列))

从包含日期的列中检索的年和月

如果年份alread存在,则不会再次创建它
如果该年下的月份存在,则不会再次创建该月份
如果该文件名已存在于该年/月下,则不会再次创建该文件名,但该文件名的附加属性将添加到属性-“行分隔?”

所需输出:

我尝试了一个Linq查询,以开始输出可能需要的XML,以便继续进行,但它输出每一行,并且不进行分组,我目前不熟悉Linq

我还遇到了.Split(“,”)上的基本转义的问题(请参阅上面的原始CSV示例,与我在测试文件和下面的示例中使用制表符分隔的情况相比),这就是我希望Oledb提供程序处理它的原因

string[] source = File.ReadAllLines(@"C:\Processing\In\mockCsv.csv");
XElement item = new XElement("Root",
    from str in source
    let fields = str.Split('\t')
    select new XElement("Year", fields[4].Substring(0, 4),
    new XElement("Month", fields[4].Substring(5, 2),
        new XElement("FileName", fields[3]),
        new XElement("Description",fields[0]),
        new XElement("Length", fields[1]),
        new XElement("Type", fields[2]),
        new XElement("FileName", fields[3]),
        new XElement("Date", fields[4]),
        new XElement("Authorised", fields[5]))
        )                
);
我还需要记录过程中的每个步骤,因此我设置了一个Logger类

private class Logger
{
    private static string LogFile = null;

    internal enum MsgType
    {
        Info,
        Debug,
        Error
    }

    static Logger()
    {
        var processingDetails = ConfigurationManager.GetSection(SECTION_PROCESSINGDETAILS) as NameValueCollection;
        LogFile = Path.Combine(processingDetails[KEY_WORKINGFOLDER],
                                String.Format("Log_{0}.txt", StartTime.ToString("MMMyyyy")));
        if (File.Exists(LogFile))
            File.Delete(LogFile);
    }

    internal static void Write(string msg, MsgType msgType, bool isNewLine, bool closeLine)
    {
        if (isNewLine)
            msg = String.Format("{0} - {1} : {2}", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"), msgType, msg);

        if (closeLine)
            Console.WriteLine(msg);
        else
            Console.Write(msg);

        if (String.IsNullOrEmpty(LogFile))
            return;

        try
        {
            using (StreamWriter sw = new StreamWriter(LogFile, true))
            {
                if (closeLine)
                    sw.WriteLine(msg);
                else
                    sw.Write(msg);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}
这样使用

Logger.Write(String.Format("Reading records from csv file ({0})... ",
            csvFile), Logger.MsgType.Info, true, false);

试试下面的。如果从文件读取,请使用StreamReader而不是StringReader:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Text.RegularExpressions;


namespace ConsoleApplication74
{
    class Program
    {

        static void Main(string[] args)
        {
            string input =
                        "\"DESCRIPTION1\",\"8, 5/8 X 6.4MM\",\"STRING\",\"filename001.pdf\",\"2016-09-19\",\"1\"\n" +
                        "\"DESCRIPTION2\",\"12, 3/4 X 6.4MM\",\"STRING\",\"filename001.pdf\",\"2016-09-19\",\"1\"\n" +
                        "\"DESCRIPTION3\",\"12, 3/4 X 6.4MM\",\"STRING\",\"filename001.pdf\",\"2016-09-19\",\"1\"\n" +
                        "\"another description 20# gw\",\"1\",\"388015\",\"Scan123.pdf\",\"2015-10-24\",\"1\"\n" +
                        "\"another description 20# gw\",\"3\",\"385902\",\"Scan456.pdf\",\"2015-04-14\",\"1\"\n" +
                        "\"STRINGVAL1\",\"273.10 X 9.27 X 6000\",\"45032-01\",\"KHJDWNEJWKFD9101529.pdf\",\"2012-02-03\",\"1\"\n" +
                        "\"STRINGVAL2\",\"273.10 X 21.44 X 6000\",\"7-09372\",\"DJSWH68767681540.pdf\",\"2017-02-03\",\"1\"\n";

            string pattern = "\\\"\\s*,\\s*\\\"";

            string inputline = "";
            StringReader reader = new StringReader(input);

            XElement root = new XElement("Root");
            while ((inputline = reader.ReadLine()) != null)
            {
                string[] splitLine = Regex.Split(inputline,pattern);
                Item newItem = new Item() {
                    description = splitLine[0].Replace("\"",""),
                    length = splitLine[1],
                    type = splitLine[2],
                    filename = splitLine[3],
                    date = DateTime.Parse(splitLine[4]),
                    authorized = splitLine[5].Replace("\"", "") == "1" ? true : false
                };

                Item.items.Add(newItem);
            }

            foreach(var year in Item.items.GroupBy(x => x.date.Year).OrderBy(x => x.Key))
            {
                XElement newYear = new XElement("_" + year.Key.ToString());
                root.Add(newYear);
                foreach(var month in year.GroupBy(x => x.date.Month).OrderBy(x => x.Key))
                {
                    XElement newMonth = new XElement("_" + month.Key.ToString());
                    newYear.Add(newMonth);

                    newMonth.Add(
                        month.OrderBy(x => x.date).Select(x => new XElement(
                            x.filename,
                            string.Join("\r\n", new object[] {
                                x.description,
                                x.length,
                                x.type,
                                x.date.ToString(),
                                x.authorized.ToString()
                            }).ToList()
                    )));
                }
            }
        }

    }
    public class Item
    {
        public static List<Item> items = new List<Item>();

        public string description { get; set; }
        public string length { get; set; }
        public string type { get; set; }
        public string filename { get; set; }
        public DateTime date { get; set; }
        public Boolean authorized { get; set; }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Xml;
使用System.Xml.Linq;
使用System.IO;
使用System.Text.RegularExpressions;
命名空间控制台应用程序74
{
班级计划
{
静态void Main(字符串[]参数)
{
字符串输入=
“描述1\”、“8,5/8 X 6.4MM\”、“字符串\”、“文件名001.pdf\”、“2016-09-19\”、“1\”\n+
“描述2\”、“12,3/4 X 6.4MM\”、“字符串\”、“文件名001.pdf\”、“2016-09-19\”、“1\”\n+
“描述3\”、“12,3/4 X 6.4MM\”、“字符串\”、“文件名001.pdf\”、“2016-09-19\”、“1\”\n+
“另一个描述20千兆瓦”,“1”,“388015”,“Scan123.pdf”,“2015-10-24”,“1\”\n”+
“另一个描述20千兆瓦”,“3”,“385902”,“Scan456.pdf”,“2015-04-14”,“1\”\n”+
““STRINGVAL1\”、“273.10 X 9.27 X 6000\”、“45032-01\”、“KHJDWNEJWKFD9101529.pdf\”、“2012-02-03\”、“1\”\n”+
“STRINGVAL2\”、“273.10 X 21.44 X 6000\”、“7-09372\”、“DJSWH68767681540.pdf\”、“2017-02-03\”、“1\”\n”;
字符串模式=“\\\”\\s*,\\s*\\\”;
字符串inputline=“”;
StringReader=新的StringReader(输入);
XElement根=新XElement(“根”);
而((inputline=reader.ReadLine())!=null)
{
string[]splitLine=Regex.Split(inputline,pattern);
Item newItem=新项(){
description=splitLine[0]。替换(“\”,“),
长度=分割线[1],
类型=分割线[2],
filename=splitLine[3],
date=DateTime.Parse(拆分行[4]),
authorized=splitLine[5]。替换(“\”,”)=“1”?真:假
};
Item.items.Add(newItem);
}
foreach(Item.items.GroupBy(x=>x.date.year.OrderBy(x=>x.Key))中的var年)
{
XElement newYear=newXelement(“”+year.Key.ToString());
root.Add(新年);
foreach(var年中的月数.GroupBy(x=>x.date.month).OrderBy(x=>x.Key))
{
XElement newMonth=newXelement(“”+month.Key.ToString());
newYear.Add(newMonth);
新月份。添加(
month.OrderBy(x=>x.date)。选择(x=>new-XElement(
x、 文件名,
string.Join(“\r\n”,新对象[]{
x、 描述,
x、 长度,
x、 类型,
x、 date.ToString(),
x、 authorized.ToString()
})托利斯先生()
)));
}
}
}
}
公共类项目
{
公共静态列表项=新列表();
公共字符串说明{get;set;}
公共字符串长度{get;set;}
公共字符串类型{get;set;}
公共字符串文件名{get;set;}
公共日期时间日期{get;set;}
公共布尔授权{get;set;}
}
}

我不清楚您的问题是什么。你不能解析CSV吗?或者您不知道如何从内存中的对象创建xml?请更新一个问题,使其更加具体。我不确定如何将csv中的对象分组,然后在topUse.Net的
TextFieldParser
上使用分组属性以所需的不同格式输出为XML。无论如何,你在一个问题上问得太多了。谢谢,现在已经很晚了,我已经运行了它并查看了输出,我想我可以稍微操纵一下它,给我一些东西来处理,谢谢你的时间(我给了你