C# .net使用xml将csv映射到类
我的任务是读取csv文件并将内容写入c#List。 由于csv文件将来可以更改其布局(标题/顺序),因此我希望使用配置文件映射属性 现在我想知道是否有一个例子,这样我就不必重新发明weel:D了 我的数据源如下所示(制表位分隔) 我的班级是这样的:C# .net使用xml将csv映射到类,c#,xml,csv,mapping,C#,Xml,Csv,Mapping,我的任务是读取csv文件并将内容写入c#List。 由于csv文件将来可以更改其布局(标题/顺序),因此我希望使用配置文件映射属性 现在我想知道是否有一个例子,这样我就不必重新发明weel:D了 我的数据源如下所示(制表位分隔) 我的班级是这样的: Class Customer { string CustomerNo {get;set;} string CustomerName {get;set;} DateTime CreatedOn {get;set;} de
Class Customer
{
string CustomerNo {get;set;}
string CustomerName {get;set;}
DateTime CreatedOn {get;set;}
decimal Discount {get;set;}
}
现在,我希望有一个具有该定义的外部xml文件,这样我就可以在运行时修改它,而无需重新编译代码
<customermapping mapstoclass="my.namespace.Customer">
<attribute csvcaption="Customer No." mapstoproperty="CustomerNo"
typeof="System.String" required="true">
<attribute csvcaption="Customer Name" mapstoproperty="CustomerName"
typeof="System.String" required="true">
<attribute csvcaption="Created" mapstoproperty="CreatedOn"
typeof="System.DateTime" required="false">
<attribute csvcaption="Discount" mapstoproperty="Discount"
typeof="System.Decimal" required="false">
</customermapping>
在一天结束时,我想做以下事情:
(我已经可以读取csv文件中的所有值(第一行是标题,位于单独的数组中)
列出客户=
CreateCustomerList(字符串[]csvCaptions,字符串[]csvLines,
“c:\customermapping.xml”);
应该不会太复杂,但正如我所说的,如果有人已经做了类似的事情,欢迎提供任何示例。看起来您希望重新创建xsd模式。如果您可以更改格式,请使用xml并在xml中定义该规则
如果您无法更改格式,或者您的数据太大,无法很好地适应xml,我想您只能靠自己了。CSV并不是一种临时格式,我认为没有任何机构愿意为其创建架构验证。您可能需要研究使用LINQ来实现此目的。这里有一篇关于LINQ的文章:
如果你能帮上忙的话,我会把逻辑放在代码中哪些列映射到哪些属性上,而不是放在xml文件中。我不想重新发明xsd。我想
使用xml来定义数据和类之间的映射。就像nhibernate将数据库表映射到类属性上。正如我所说的,实现起来应该不会太复杂但可能有一个通用的解决方案。@Schlaviener我的意思是你想创建类似xsd for csv的东西。我只是建议使用xml而不是csv,并使用xsd来定义映射。然后你可以使用xsd.exe在对象和xml文件之间映射创建映射。您好,有没有合适的工作解决方案…我很高兴正在经历同样的问题。。。thanks@jalchr:没有,但在我的上一个项目中,我使用了CsvHelper(来自nuget)这太棒了。应该可以用代码创建配置并将其序列化为xml。实际上,我对另一种方式感兴趣。我需要用xml定义配置,并将其应用于标准类模型的传入文件。有什么想法吗?
<customermapping mapstoclass="my.namespace.Customer">
<attribute csvcaption="Customer No." mapstoproperty="CustomerNo"
typeof="System.String" required="true">
<attribute csvcaption="Customer Name" mapstoproperty="CustomerName"
typeof="System.String" required="true">
<attribute csvcaption="Created" mapstoproperty="CreatedOn"
typeof="System.DateTime" required="false">
<attribute csvcaption="Discount" mapstoproperty="Discount"
typeof="System.Decimal" required="false">
</customermapping>
List<Customer> customers =
CreateCustomerList(string[] csvCaptions, string[] csvLines,
"c:\customermapping.xml");