Click here to Skip to main content
Click here to Skip to main content

XML Serialization and deSerialization

By , 22 Apr 2008
Rate this:
Please Sign up or sign in to vote.

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.Colloction.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 Instaces 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 Instaces 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 Instaces 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 Instaces 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 that 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 thr 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 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 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>

License

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

About the Author

mukeshkumar123
Web Developer IBM
India India
No Biography provided

Comments and Discussions

 
GeneralGud and very usefull article Pinmemberchintan_shah_ibm22-Apr-08 21:17 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140415.2 | Last Updated 22 Apr 2008
Article Copyright 2008 by mukeshkumar123
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid