This is a mirror of official site: http://jasper-net.blogspot.com/

XML Serialization of Arrays and Collections

| Monday, July 11, 2011
Serializing Arrays and Collections

When you serialize an object that contains arrays or collections to XML, an element is created based upon the name of the property or field. This contains one child element for each item in the array. The names of the child elements match the data type names for the items. Sometimes you will want to modify this behaviour to change the element naming or to adjust other details, such as adding namespaces or controlling the serialization of different item data types.

This article describes how the serialization can be modified. We will use two test classes for this purpose. One class describes an employee of a business. The second represents a department within the company, which can include a number of employees in a simple generic list. The classes are shown below:

public class Department
{
    public string Name { get; set; }

    public List<Employee> Employees { get; set; }

    public Department()
    {
        Employees = new List<Employee>();
    }
}

public class Employee
{
    public string Name { get; set; }

    public Employee() { }

    public Employee(string name)
    {
        Name = name;
    }
}

The examples will all serialize a sample department and its employees using the code below. This will be the same for all samples. The only changes will be to attributes of the Department type.

Department dept = new Department();
dept.Name = "IT";
dept.Employees.Add(new Employee("Bob"));
dept.Employees.Add(new Employee("Jim"));
dept.Employees.Add(new Employee("Mel"));

XmlSerializer serializer = new XmlSerializer(dept.GetType());
using (StreamWriter writer = new StreamWriter(@"d:\Department.xml"))
{
    serializer.Serialize(writer, dept);
}

Read more: Black Wasp
QR: XMLArrays.aspx

Posted via email from Jasper-net

0 comments: