abdelwaheb ammar

abdelwaheb ammar

  • 1.3k
  • 457
  • 123.9k

serialize a list of object

May 13 2020 4:36 AM
hi, i want to serialize an objects to xml file of a Departement contain a list of Employees.this is my code C# which i putted:
  1. public class Department    
  2. {    
  3.     public string Name { getset; }    
  4.     public List<Employee> Employees { getset; }    
  5.     public Department()    
  6.     {    
  7.         Employees = new List<Employee>();    
  8.     }    
  9. }    
  10.      
  11. public class Employee    
  12. {    
  13.     public string Name { getset; }    
  14.     public Employee() { }    
  15.     public Employee(string name)    
  16.     {    
  17.         Name = name;    
  18.     }    
  19. }    
  20.     
  21. Department dept = new Department();    
  22. dept.Name = "IT";    
  23. dept.Employees.Add(new Employee("Bob"));    
  24. dept.Employees.Add(new Employee("Jim"));    
  25. dept.Employees.Add(new Employee("Mel"));    
  26. XmlSerializer serializer = new XmlSerializer(dept.GetType());    
  27. using (StreamWriter writer = new StreamWriter(@"d:\Department.xml"))    
  28. {    
  29.     serializer.Serialize(writer, dept);    
  30. }  
this code generate succefully a file xml like this:
  1. <Department>    
  2.   <Name>IT</Name>    
  3.   <Employees>    
  4.     <Employee>    
  5.       <Name>Bob</Name>    
  6.     </Employee>    
  7.     <Employee>    
  8.       <Name>Jim</Name>    
  9.     </Employee>    
  10.     <Employee>    
  11.       <Name>Mel</Name>    
  12.     </Employee>    
  13.   </Employees>    
  14. </Department>    
but my goal is to get that like this:
  1. <Department>    
  2.   <Name>IT</Name>    
  3.      <Employee>    
  4.       <Name>Bob</Name>    
  5.     </Employee>    
  6.     <Employee>    
  7.       <Name>Jim</Name>    
  8.     </Employee>    
  9.     <Employee>    
  10.       <Name>Mel</Name>    
  11.     </Employee>    
  12. </Department>  
that's mean i want to erase the <Employees> Element
 
how can i fix this?

Answers (2)