XML Serialization in .NET Framework 2.0 : Part II

Introduction:

In the previous
article we have learnt how to use XML Serialization with .NET Framework Data Types. In this article we will learn how to make your class support XML Serialization.

How to create classes that can be Serialized by using XML Serialization:

To create a class that can be serialized by using XML serialization, you must perform the following tasks:

  • Specify the class as public.
  • Specify all members that must be serialized as public.
  • Create a parameterless constructor.

Unlike classes processed with standard serialization, classes do not have to have the Serializable attribute to be processed with XML serialization. If there are private or protected members, they will be skipped during serialization.

Example:

public class Student

{

    public Int32 studentId;

    public decimal age;

    public string studentName;

 

    public Student()

    {

 

    }
}

Serializing an instance of this class with sample values creates the following XML (which has been slightly simplified for readability):


<?
xml version="1.0" ?>

<Student>

  <studentId>100</studentId>

  <age>15.5</age>

  <studentName>"Ahmed"</studentName>
</Student>

How to Control XML Serialization:

You can control XML Serialization using some attributes in .NET Framework 2.0. You can find them in
http://msdn2.microsoft.com/en-us/library/2baksw0z.aspx

For the scope of the this article we will be exposed to a couple of theses attributes.

For example, consider the attributes required to make the following three changes to the serialized XML document:

  1. Change the Student element name to SchoolStudent.
  2. Make studentId an attribute of SchoolStudent, rather than a separate element.
  3. Do not include the age in the serialized document.

[XmlRoot("SchoolStudent")]

public class Student

{

    [XmlAttribute]

    public Int32 studentId;

    [XmlIgnore]

    public decimal age;

    public string studentName;

 

    public Student()

    {

 

    }
}

Serializing an instance of this class with sample values creates the following XML(which has been slightly simplified for readability):

<?xml version="1.0" ?>

<SchoolStudent studentId="100">

  <studentName>"Ahmed"</studentName>

</SchoolStudent>

Summary:

  • To create a class that can be serialized, specify the class and all members as public, and create a parameterless constructor.
  • You can control XML serialization by using attributes. Attributes can change the names of elements, serialize members as attributes rather than elements, and exclude members from serialization.

Up Next
    Ebook Download
    View all
    Learn
    View all