I am trying to load XML data that consists of a collection of Employee objects. The following function works fine for properties that are simple data types like String and Int. I am wondering how can I import data types of complex type. For example,
This function works fine:
private void LoadData()
{
XDocument employeesDoc = XDocument.Load("Employees.xml");
List<Employee> data = (from employee in employeesDoc.Descendants("Employee")
select new Employee
{
FirstName= employee.Attribute("FirstName").Value,
LastName = employee.Attribute("LastName ").Value,
PhoneNumber = employee.Attribute("PhoneNumber").Value
}).ToList();
Employees.ItemsSource = data;
}
Here is the Employee class:
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
public Department Department { get; set; }
}
Here is the Department class:
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Employee Manager { get; set; }
}
So, if my XML file looks like so:
<Employees>
<Employee FirstName="John" LastName="Summers" PhoneNumber="703-548-7841" Department="Finance"></Employee>
<Employee FirstName="Susan" LastName="Hughey" PhoneNumber="549-461-7962" Department="HR"></Employee>
So, if the Department is a complex object and it is a string in XML file, how can I change my LoadData() function to import it into my Employee object collection?