A few days back I had to de-serialize data from xml file to my List class.
my approach was like this:
private void button1_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load("Test.xml");
XmlSerializer xs = new XmlSerializer(typeof(UserHolder));
UserHolder uh = (UserHolder)xs.Deserialize(new StringReader(doc.OuterXml));
dataGridView1.DataSource = uh.Users.ToDataTable();
}
public class User
{
[XmlElement("id")]
public Int32 Id { get; set; }
[XmlElement("name")]
public String Name { get; set; }
}
[XmlRoot("user_list")]
public class UserHolder
{
private List<User> users = null;
public UserHolder()
{
users = new List<User>();
}
[XmlElement("user")]
public List<User> Users
{
get { return users; }
set { users = value; }
}
}
public static class Convert2Table
{
public static DataTable ToDataTable<T>(this IList<T> list)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in list)
{
for (int i = 0; i < values.Length; i++)
values[i] = props[i].GetValue(item) ?? DBNull.Value;
table.Rows.Add(values);
}
return table;
}
}
The code above works fine, but I had to write many lines of code.
I now have a new situation where I have a customer class and one datatable. My datatable is populated with multiple customers data. I want to deserialize that data from datatable to my customer class. How can I do that more efficiently than I did before? I doubt linq will help me. So please guide me for deserialize datatable data to my customer class List.
Like this:
And so on for all the properties of
Customer