Thursday, February 16, 2017

Serialize .NET Classes with Inheritance to XML

Good day!
Here's a simple example on how to Serialize .NET classes that applied the concept of Inheritance to XML. Given the model classes below:
public class Employee
 public int EmployeeId { get; set; }
 public string Name { get; set; }
 public string Address { get; set; }

public class Utility : Employee
 public string Category { get; set; }

public class Supervisor : Employee
 public int OverrideCode { get; set; }
The code to populate and serialize the objects to XML is presented here using XmlSerializer class:
List<Employee> employees = new List<Employee>();

Supervisor supervisor1 = new Supervisor();
supervisor1.Name = "Michael";
supervisor1.Address = "Manila";
supervisor1.EmployeeId = 11111;
supervisor1.OverrideCode = 234;

Utility utility1 = new Utility();
utility1.Name = "Erick";
utility1.Address = "Masbate";
utility1.EmployeeId = 33333;
utility1.Category = "Bus Driver";

Supervisor supervisor2 = new Supervisor();
supervisor2.Name = "James";
supervisor2.Address = "Cebu";
supervisor2.EmployeeId = 22222;
supervisor2.OverrideCode = 567;

 XmlSerializer serializeEmployees = new XmlSerializer(typeof(List<Employee>), 
  new Type[] { typeof(Supervisor), typeof(Utility) });
 serializeEmployees.Serialize(File.Create(@"C:\Codes\Employees.xml"), employees);
catch (Exception )
Note: If you do not specify the types in the second parameter of Serialize() method, this will create an exception {"The type [Namespace].Class was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."}
XML Output
<?xml version="1.0"?>
<ArrayOfEmployee xmlns:xsi="" xmlns:xsd="">
  <Employee xsi:type="Supervisor">
  <Employee xsi:type="Utility">
    <Category>Bus Driver</Category>
  <Employee xsi:type="Supervisor">


Post a Comment