C#: How to initialize a generic list via reflection?

I have a list of object properties read from xml file and want to create the object through reflection (not xml serialization). For example, I have a property

List<Employee> Employees { get; set; }

I want to initialize this list from the follwing xml file:

<Employees>
  <Employee>
    <FirstName>John</FirstName>
    <LastName>Zak</LastName>
    <Age>20</Age>
  </Employee>
</Employees>

I could create the Employees object dynamically though e.g.

  Type employees = (type of Employees through reflection)
  object obj = Activator.CreateInstance(employees);

My problem is how can I populate the Employees list? I want to do it in a generic way (no cast to Employee) to make this code reusable.

Answers


If I understand your question correctly, this should do (employees and obj variables are from your code):

var employee = BuildEmployeeFromXml();
employees.GetMethod("Add").Invoke(obj, new[] {employee});
// repeat the above for as many employee objects you have
Console.WriteLine(list);

The code assumes you already know how to build the employee object from the XML in the BuildEmployeeFromXml() method. If you don't, refer to my library Fasterflect for quick & easy way to construct objects using reflection.


Why use Reflection?

This is something that the XmlSerializer should be able to handle for you.

LINQ to XML is also a possibility (especially if you're coding to a changing XML document). The code used to construct an object from XML with LINQ to XML is better suited to handle changes in the XML format.

Nevermind...LINQ to XML isn't going to help you if you're targeting .NET 2.0.


Need Your Help

How do I use the information in one xml file to create another in C#?

c# xml xml-parsing

I have a really large xml file that has some information I am interested in, but I need to present it in another way. Let me illustrate:

JPA & PostgreSQL: How do I call a stored procedure with void return type?

java postgresql jpa plpgsql

I'm trying to call a PL/pgSQL function that executes an update (language sql, returns void). I'm getting this exception:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.