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:
[Serializable]
public class Employee
{
 public int EmployeeId { get; set; }
 public string Name { get; set; }
 public string Address { get; set; }
}

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

[Serializable]
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;
employees.Add(supervisor1);

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

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


try
{
 XmlSerializer serializeEmployees = new XmlSerializer(typeof(List<Employee>), 
  new Type[] { typeof(Supervisor), typeof(Utility) });
 serializeEmployees.Serialize(File.Create(@"C:\Codes\Employees.xml"), employees);
}
catch (Exception )
{
 //TODO
}
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="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Employee xsi:type="Supervisor">
    <EmployeeId>11111</EmployeeId>
    <Name>Michael</Name>
    <Address>Manila</Address>
    <OverrideCode>234</OverrideCode>
  </Employee>
  <Employee xsi:type="Utility">
    <EmployeeId>33333</EmployeeId>
    <Name>Erick</Name>
    <Address>Masbate</Address>
    <Category>Bus Driver</Category>
  </Employee>
  <Employee xsi:type="Supervisor">
    <EmployeeId>22222</EmployeeId>
    <Name>James</Name>
    <Address>Cebu</Address>
    <OverrideCode>567</OverrideCode>
  </Employee>
</ArrayOfEmployee>

0 comments:

Post a Comment