XML Serialization of Collections

Files and Directories

XMLA few days ago I wrote an article on basic XML serialization which looked at the XML serialization of an Employee object that we created. In this article I am going to build on that previous article by serializing a collection of Employee objects, so if you have not read Basic XML Serialization in C# I suggest you do that before reading this article.

Sometimes a developer would need to serialize a collection of objects such as a List or an ArrayList. In this article I am going to show you how to serialize a List of Employee objects to an XML file.

We are going to use the Employee class we created in the Basic XML Serialization in C# article. Then we are going to create another class which will be the collection class for our Employee class. We can call it EmployeeList. Below is what this class should look like:

using System;
using System.Xml.Serialization;
using System.Collections.Generic;

namespace XMLSerialization
{  
    [XmlRoot("CompanyEmployees")]
    public class EmployeeList
    {
        [XmlArray("EmployeeListing")]

        [XmlArrayItem("Employee", typeof(Employee))]
        public List employeeList;

        // Constructor
        public EmployeeList()
        {
            employeeList = new List();
        }

        public void AddEmployee(Employee employee)
        {
            employeeList.Add(employee);
        }
    }
}

As you can see, the above code contains strange lines of code in square brackets ‘[ ]’. In C# these are called Attributes and their purpose is to add metadata to your program. In our case these attributes are adding metadata for the xml serializer to know how to build an xml file out of the serialized objects.

The XmlRoot attribute allows you to set information for the root XML node which will be created in the serialized file. Such information includes the namespace, the element name, the data type, etc, but for our example we will only be using the ElementName, and we are setting it to CompanyEmployees.

Next we are setting the XmlArray attribute which tells the serializer that it must serialize a particular class member as an array of XML elements. We are assigning the ElementName to EmployeeListing.

Then we are creating a list of employees – List<Employee>, and assigning the XmlArrayItem attribute which specifies the type of class our collection contains. In this case it is Employee since we have a List of Employee objects. We are also going to use the name Employee for each employee XML node.

Next we are setting up the class constructor, and finally we are declaring the AddEmployee() method which simply adds Employee objects to our employeeList.

Now for the actual XML serialization code:

private void SerializeList()
{
    // Create an instance of the EmployeeList class
    EmployeeList employeeList = new EmployeeList();

    // Create a few instances of the Employee class
    Employee emp1 = new Employee();
    emp1.Name = "John";
    emp1.Surname = "Smith";
    emp1.DateOfBirth = new DateTime(1980, 10, 08);
    emp1.Sex = Employee.EmployeeSex.Male;
    emp1.Position = "Software Engineer";

    Employee emp2 = new Employee();
    emp2.Name = "David";
    emp2.Surname = "McGregor";
    emp2.DateOfBirth = new DateTime(1973, 01, 13);
    emp2.Sex = Employee.EmployeeSex.Male;
    emp2.Position = "Product Manager";

    Employee emp3 = new Employee();
    emp3.Name = "Sarah";
    emp3.Surname = "Crow";
    emp3.DateOfBirth = new DateTime(1983, 11, 23);
    emp3.Sex = Employee.EmployeeSex.Female;
    emp3.Position = "Software Tester";

    // Add the employees to the list   
    employeeList.AddEmployee(emp1);
    employeeList.AddEmployee(emp2);
    employeeList.AddEmployee(emp3);

    // Create an instance of System.Xml.Serialization.XmlSerializer
    XmlSerializer serializer = new XmlSerializer(employeeList.GetType());

    // Create an instance of System.IO.TextWriter 
    // to save the serialized object to disk
    TextWriter textWriter = new StreamWriter("C:\\Employee\\employeeList.xml");

    // Serialize the employeeList object
    serializer.Serialize(textWriter, employeeList);

    // Close the TextWriter
    textWriter.Close();
}

As can be seen in the above code, we are creating three instances of the Employee class and adding them to an instance of the EmployeeList class. We are then serializing the employeeList object and we end up with an XML file looking like this:

<?xml version="1.0" encoding="utf-8"?>
<CompanyEmployees xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <EmployeeListing>
    <Employee>
      <Name>John</Name>
      <Surname>Smith</Surname>
      <DateOfBirth>1980-10-08T00:00:00</DateOfBirth>
      <Sex>Male</Sex>
      <Position>Software Engineer</Position>
    </Employee>
    <Employee>
      <Name>David</Name>
      <Surname>McGregor</Surname>
      <DateOfBirth>1973-01-13T00:00:00</DateOfBirth>
      <Sex>Male</Sex>
      <Position>Product Manager</Position>
    </Employee>
    <Employee>
      <Name>Sarah</Name>
      <Surname>Crow</Surname>
      <DateOfBirth>1983-11-23T00:00:00</DateOfBirth>
      <Sex>Female</Sex>
      <Position>Software Tester</Position>
    </Employee>
  </EmployeeListing>
</CompanyEmployees>

As you can see all three objects within the employeeList were dumped to the XML file. That was quite simple now wasn’t it? 🙂

Now let’s create a deserialize method:

private void DeserializeList()
{
    // Create an instance of the EmployeeList class
    EmployeeList employeeList = new EmployeeList();

    // Create an instance of System.Xml.Serialization.XmlSerializer
    XmlSerializer serializer = new XmlSerializer(employeeList.GetType());

    // Create an instance of System.IO.TextReader 
    // to load the serialized data from disk
    TextReader textReader = new StreamReader("C:\\Employee\\employeeList.xml");

    // Assign the deserialized object to the new employeeList object
    employeeList = (EmployeeList)serializer.Deserialize(textReader);

    // Close the TextReader
    textReader.Close();
}

The above code is very similar to the code I had explained in the Basic XML Serialization in C# article so if you do not understand it have a look at that article.

The below screenshot is displaying the Visual Studio Locals window and you can see the employeeList object after the deserialization process which confirms that the XML file was deserialized correctly.

Click for full size image.

Click for full size image.

With this article I have covered most of the basics of XML Serialization in C#.NET. I hope you enjoyed it and found it useful. In the future I will be talking about Binary Serialization in C# which has a few advantages over XML Serialization so stay tuned for more.

Dave

4 comments… add one
  • ltcomd Link Reply

    Thanks! 🙂

  • Leszek Link Reply

    Hi,

    How to make XMLSerializer generating attribute Sequence=”@counter” on Employee element?

Leave a Comment

Cancel reply