.net using xml for mapping csv to class
I have a Task where I have to read an csv file and write the content into a c# List. Since the csv file can change its layout (caption/order) in the future I want to use a configuration file for mapping the attributes.
Now I am wondering if there is an example out there so I don't have to reinvent the weel :D
My datasource looks like this (tab stop seperated)
Customer No. Customer Name Created Discount
10215 John Doe 2010-08-25 5050.23
And my class like this:
Class Customer
{
string CustomerNo {get;set;}
string CustomerName {get;set;}
DateTime CreatedOn {get;set;}
decimal Discount {get;set;}
}
Now I want to have an external xml file with the definition so I can modify it at runtime without recompiling the code.
<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" mapstoproper开发者_运维问答ty="Discount"
typeof="System.Decimal" required="false">
</customermapping>
At the end of the Day I want to do the following: (I already can read all the values from the csv file (the first line is the caption and is in a seperate array)
List<Customer> customers =
CreateCustomerList(string[] csvCaptions, string[] csvLines,
"c:\customermapping.xml");
Shouldn't be to complicated but as I said, if someone already did something similar, any examples are welcome.
It looks like you want to reinvent the xsd schema. If you can change the format use the xml and define that rules in the xml.
If you can't change the format or your data is too large to fit nicely in to xml I guess you are on your own. CSV isn't rather an adhoc format I don't think any body cared enough to create a schema validation for it.
You might want to look into using LINQ for this. There is an articles on LINQ to TEXT here:
- Tutorial Reading A Text File Using LINQ
- LINQ to TEXT and LINQ to CSV
Update: I've re-read your question and I'm no longer sure that using LINQ will really help solve your problem, however I'm leaving the answer here just in case it helps.
If you can at all help it I would put the logic about what columns map onto what properties in code rather than in xml files.
精彩评论