Optional Serialization of object property using XmlSerializer

By Jatin Prajapati

Shows how to optionallyy serialize a property of object using XmlSerialier.

We know that in Xml Serialization to control the generated XML we provide attributes to the class properties or variables. For example to specify a differnt XML name to a serialized property, we apply XmlElementAttribute to the public field or property. To igore a public field or propertry from serialization we provide XmlIgnoreAttribute. In some cases we need some properties to be serialized when they have value and being not serialized when they don't have value.
If the schema has an element that is optional means its minimal occurance is zero or if the schema includes a default value, we have two options. One option is to use System.ComponentModel.DefaultValueAttribute to specify default value as show in the below code.

public class Test
{
[System.ComponentModel.DefaultValueAttribute("2000")]
public string StartIndex;
}

Other option is a special pattern recognized by XmlSerializer. In this pattern an extra Boolean field is created and XmlIgnoreAttribute is applied to this field. The naming pattern is of form propertyNameSpecified. For example, if there is a field named "Item3" you will also create a field named "Item3Specified" which guides the XmlSerializer whether to generate the XML element named Item3 or not. Following is the example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;

namespace TestCS
{
    static class Program
    {
         /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
         static void Main()
        {
             //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Form1());

            TestClass classWithOutItem3 = new TestClass("My item1", "My Item2");
            TestClass classWithItem3 = new TestClass("My item1", "My Item2", "My Item3");

           XmlSerializer serialier = new XmlSerializer(typeof(TestClass));

           MemoryStream msWithOutItem3 = new MemoryStream();
           StreamWriter swWithOutItem3 = new StreamWriter(msWithOutItem3);
             serialier.Serialize(swWithOutItem3, classWithOutItem3);
             msWithOutItem3.Position = 0;
           StreamReader srWithOutItem3 = new StreamReader(msWithOutItem3);
           Console.WriteLine(srWithOutItem3.ReadToEnd());

           MemoryStream msWithItem3 = new MemoryStream();
           StreamWriter swWithItem3 = new StreamWriter(msWithItem3);
             serialier.Serialize(swWithItem3, classWithItem3);
             msWithItem3.Position = 0;
           StreamReader srWithItem3 = new StreamReader(msWithItem3);
           Console.WriteLine(srWithItem3.ReadToEnd());

           Console.ReadLine();
        }
     }

    public class TestClass
    {
         public string Item1;
        public string Item2;
        public string Item3;

        [XmlIgnore]
        public bool Item3Sepcified;

        public TestClass()
        {
            Item3Sepcified = false;
        }

         public TestClass(string item1, string item2)
        {
            Item1 = item1;
            Item2 = item2;
            Item3Sepcified = false;
        }

         public TestClass(string item1, string item2, string item3)
        {
            Item1 = item1;
            Item2 = item2;
            Item3 = item3;
            Item3Sepcified = true;
        }
     }
}

Optional Serialization of object property using XmlSerializer  (1650 Views)