65.9K
CodeProject is changing. Read more.
Home

XML Serialization and Deserialization

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.78/5 (26 votes)

Apr 22, 2008

CPOL

3 min read

viewsIcon

75541

downloadIcon

1114

This is a sample Windows application on how .NET does serialization and deserialization of strongly typed custom collection, while handling derived collection items.

Introduction

This is a sample Windows application on how .NET does serialization and deserialization of strongly typed custom collection, while handling derived collection items. Implementers are encouraged to extend this base class instead of creating their own.

Brief Description of XML Serialization

  • XML serialization can only be applied to classes that contain a public default constructor.
  • Read -only class properties are not serialized. If a property in the class only gets an accessor and does not set an accessor as well, that property will not be serialized.
  • Only Public properties and fields are serialized, Private properties are not serialized.

Example: According to Sample Windows Application

The following code snippet shows that the EmployeesList class serializes with public fields as XmlElementAttribute.

[Serializable]
public class EmployeesList
{
    // XmlElementAttribute-> public property
    will be serialized as an //element in the xml node.
        [System.Xml.Serialization.XmlElementAttribute("Employee")]
        public Employee[] Employees;
        [Serializable]
        public class Employee
        {
            private string _firstName;
            [XmlElementAttribute("FirstName")]
            public string FirstName
            {
                get
                { return _firstName; } // get accessor 

                set
                { _firstName = value; } // set accessor

            }
            private string _lastName;
            [XmlElementAttribute("LastName")]
            public string LastName
            {
                get
                { return _lastName; } // get accessor 

                set
                { _lastName = value; } // set accessor
            }

            public
                Employee()
            {
                // default
                Constructor    
            }
}
  • To serialize a strongly-typed collection of objects, have the class derived from System.Colloction.CollectionBase adding Add (), Remove (), Insert () methods and an indexer. Alternatively, you can send an array of the specified type.
  • The System.Collection.Specialized namespace in the .NET Framework Class Library contains a few specialized, strongly-typed collections that can contain Strings.

Example: According to Sample Windows Application

The following code snippet shows how only a strongly-typed collection of objects, have the class derived from System.Collection.CollectionBase adding Add (), Remove (), Insert () methods.

public class EmployeesListCollection : System.Collections.CollectionBase
{
    //Adding n number of Employee's 

    public void Add(EmployeesList.Employee inst)
    {
        base.InnerList.Add(inst); 
        //Add
    }
    //Updating selected
    Employee's 
        public void Update(int
        index, EmployeesList.Employee
        inst)
    {
        base.InnerList.Insert(index,
            inst); //Insert
    }
    //Deleting selected Employee's 
    public void Delete(EmployeesList.Employee inst)
    {
        base.InnerList.Remove(inst);    
        // Remove
    }
    // Get Parent Element during
    serialization
        public EmployeesList.Employee this[int index]
    {
        get
        {
            return
                (EmployeesList.Employee)base.InnerList[index];
        }
    }
}

About the Application

This application describes Add, Update, View, Delete employee’s information into an Employees.xml file.

Employee information consists of the following details:

  • FirstName
  • LastName
  • Address1
  • Address2
  • City
  • State
  • Country
  • ZipCode
  • HomePhone
  • WorkPhone

Low Level Design

  • Class Diagram

  • Functions Description

  • EmployessUI

    private void ViewEmployeesInformation() – It gets Employees information from Employees.xml, based on that, it validates the Employees.xml and displays the Employees information.

    Example
    Private void ViewEmployeesInformation ()
    {
        1. Get Employees Information, returns Employees information as String in XML 
           format
        2. Validate Instances XML
        3. DisplayEmployees 
    }

    private void DeleteEmployeeInformation () – It deletes Employee information from Employees.xml.

    Example
    Private void UpdateEmployees ()
    {
        1. SerializeTOXMLString, returns Employees information as String in XML format
        2. Validate Instances XML
        3. DeleteEmployeesInformation
    }

    private void UpdateEmployeeInformation () – It updates Employee information into Employees.xml.

    Example
    Private void UpdateEmployee ()
    {
        1. SerializeTOXMLString, returns Employee information as String in XML format
        2. Validate Instances XML
        3. UpdateEmployeesInformation
    }

    private void AddNewEmployeeInformation () – It adds a new Employee’s information into Employees.xml.

    Example
    Private void AddNewEmployees ()
    {
        1. SerializeTOXMLString, returns Employees information as String in XML format
        2. Validate Instances XML
        3. AddNewEmployeesInformation
    }
  • Controller

    Public static string DeserializeToObject (string xmlBuffer)

    It deserializes an XML string to object.

    Public static string SerializeTOXmlString ()

    It serializes an object to an XML string.

    public string GetEmployeesInformation ()

    It gets Employee’s information from Employees.xml.

    public bool AddNewEmployeeInformation (string xmlBuffer)

    It does add a new Employee’s information to Employees.xml file.

    public bool UpdateEmployeeInformation (string xmlBuffer)

    It updates Employee’s information into Employees.xml file.

    public bool DeleteEmployeeInformation (string xmlBuffer)

    It deletes the Employee’s information from Employees.xml file.

    Public bool ValidationXml ()

    It validates the XML string format.

  • XML Schema Description

    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"
     xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="EmployeesList">
         <xs:complexType>
           <xs:sequence>
             <xs:element maxOccurs="unbounded" name="Employee">
               <xs:complexType>
                 <xs:sequence>
                   <xs:element name="FirstName" type="xs:string" />
                   <xs:element name="LastName" type="xs:string" />
                   <xs:element name="Address1" type="xs:string" />
                   <xs:element name="Address2" type="xs:string" />
                   <xs:element name="City" type="xs:string" />
                   <xs:element name="State" type="xs:string" />
                   <xs:element name="Country" type="xs:string" />
                   <xs:element name="ZipCode" type="xs:string" />
                   <xs:element name="HomePhone" type="xs:string" />
                   <xs:element name="WorkPhone" type="xs:string" />
                 </xs:sequence>
               </xs:complexType>
             </xs:element>
           </xs:sequence>
         </xs:complexType>
       </xs:element>
    </xs:schema>

    XML File Description

    <?xml version="1.0" encoding="utf-8"?>
    
    <EmployeesList
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Employee>
        <FirstName>R SHAWN</FirstName>
        <LastName>ROUNDTREE</LastName>
        <Address1>MAYFIELD STREET</Address1>
        <Address2>xy</Address2>
        <City>DEMARK</City>
        <State>SC</State>
        <Country>United States</Country>
        <ZipCode>29000</ZipCode>
        <HomePhone>379397856</HomePhone>
        <WorkPhone>37933000</WorkPhone>
      </Employee>
    <EmloyeesList>

High Level Design

Figure 1

View Employees Information

It displays all Employees information in a tabular form as shown in Figure 1.

  • Delete
  • View

Delete

It provides an option to delete the selected Employee information. On clicking the delete button, it should display a confirmation dialog box. If the user confirms, then the Employee’s information should be deleted from the Employees.xml file and from the Employee’s information view, upon cancel clicking it should be cancelled.

  • View: It provides an option to view selected Employee information as Figure 2.
  • On Viewing the button click, a dialog box displays with selected Employee information as Figure (2).

Figure 2
  • It allows the editing Employee information. Once the user saves it, it updates into the Employees.xml file. Otherwise, a user can select the cancel button to see the main window (Figure 1) without updation.

Figure 3

Add New Employee

  • It allows a user to add new Employee information into base Employees.xml.
  • Users have to fill up all textboxes information in the following window (Figure 3) and click on the save button, the same information should be added into the Employee.xml file.
  • Clear button allows to clear all textboxes information.
Before Addition of New Employee, Employees.xml as below
<?xml version="1.0" encoding="utf-8"?>

<EmployeesList
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <Employee>

    <FirstName>R SHAWN</FirstName>
    <LastName>ROUNDTREE</LastName>
    <Address1>MAYFIELD STREET</Address1>
    <Address2>xy</Address2>
    <City>DEMARK</City>
    <State>SC</State>
    <Country>United States</Country>
    <ZipCode>29000</ZipCode>
    <HomePhone>379397856</HomePhone>
    <WorkPhone>37933000</WorkPhone>
  </Employee>
<EmloyeesList>
After Addition of new Employee, Employees.xml as below
<?xml version="1.0" encoding="utf-8"?>
<EmployeesList
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Employee>
    <FirstName>R SHAWN</FirstName>
    <LastName>ROUNDTREE</LastName>
    <Address1>MAYFIELD STREET</Address1>
    <Address2>xy</Address2>
    <City>DEMARK</City>
    <State>SC</State>
    <Country>United States</Country>
    <ZipCode>29000</ZipCode>
    <HomePhone>379397856</HomePhone>
    <WorkPhone>37933000</WorkPhone>
  </Employee>

<Employee>
  <FirstName>ABC</FirstName>
  <LastName>XYZ</LastName>
  <Address1>XY</Address1>
  <Address2>XY</Address2>
  <City>Z</City>
  <State>Av</State>
  <Country>BB</Country>
  <ZipCode>324324</ZipCode>
  <HomePhone>23423</HomePhone>
  <WorkPhone>32432</WorkPhone>
</Employee>
<EmloyeesList>