Click here to Skip to main content
15,878,809 members
Articles / Desktop Programming / Windows Forms

XML Serialization and Deserialization

Rate me:
Please Sign up or sign in to vote.
3.78/5 (27 votes)
22 Apr 2008CPOL3 min read 74.4K   1.1K   33   11
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.

C#
[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.

C#
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

    Image 1

  • 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
    C#
    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
    C#
    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
    C#
    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
    C#
    Private void AddNewEmployees ()
    {
        1. SerializeTOXMLString, returns Employees information as String in XML format
        2. Validate Instances XML
        3. AddNewEmployeesInformation
    }
  • Controller

    C++
    Public static string DeserializeToObject (string xmlBuffer)

    It deserializes an XML string to object.

    C++
    Public static string SerializeTOXmlString ()

    It serializes an object to an XML string.

    C++
    public string GetEmployeesInformation ()

    It gets Employee’s information from Employees.xml.

    C++
    public bool AddNewEmployeeInformation (string xmlBuffer)

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

    C++
    public bool UpdateEmployeeInformation (string xmlBuffer)

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

    C++
    public bool DeleteEmployeeInformation (string xmlBuffer)

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

    C++
    Public bool ValidationXml ()

    It validates the XML string format.

  • XML Schema Description

    XML
    <?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
    <?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

Image 2

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).

Image 3

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.

Image 4

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
<?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
<?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>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer IBM
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 2 Pin
Elroy Dsilva15-Jun-09 16:14
Elroy Dsilva15-Jun-09 16:14 
GeneralGreat Coding dude!! Pin
way2rohit27-May-09 3:34
way2rohit27-May-09 3:34 
GeneralProblem while Deserializing the xml Pin
Mayur_Gadhave29-Apr-09 10:24
Mayur_Gadhave29-Apr-09 10:24 
GeneralCould do with some proof-reading Pin
vodzurk26-Mar-09 1:00
vodzurk26-Mar-09 1:00 
QuestionDoes XML serialization require a PUBLIC default constructor? Pin
Michael Freidgeim21-Mar-09 13:11
Michael Freidgeim21-Mar-09 13:11 
GeneralMy vote of 2 Pin
ramesh_nrk20-Jan-09 19:27
ramesh_nrk20-Jan-09 19:27 
GeneralVery Informative Pin
sandyaa3-Jul-08 0:41
sandyaa3-Jul-08 0:41 
GeneralRe: Very Informative Pin
Mukesh Kumar IBM3-Jul-08 0:57
Mukesh Kumar IBM3-Jul-08 0:57 
GeneralGood Work Pin
dev_ashi23-Apr-08 2:09
dev_ashi23-Apr-08 2:09 
GeneralGood Article for Data base type query and processing Pin
dinesh241123-Apr-08 0:13
dinesh241123-Apr-08 0:13 
GeneralGud and very usefull article Pin
chintan_shah_ibm22-Apr-08 21:17
chintan_shah_ibm22-Apr-08 21:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.