1

Suppose i have one customer class and i will serialize the class to xml. After serialization we will get xml data but i need some property of customer class to be serialized on demand based on few condition. Is it possible?

I have no concept how to do it. Can anyone help me with this?

manji
  • 47,442
  • 5
  • 96
  • 103
Mou
  • 15,673
  • 43
  • 156
  • 275

2 Answers2

2

You can add one or more ShouldSerializeXXXXXX() methods, where XXXXXX is the name of each property you want to serialize based on a condition.

E.g.:

public class Customer
{
    [DefaultValue(null)]
    public string SomeInfo { get; set; }

    [DefaultValue(null)]
    public string SomeOtherInfo { get; set; }

    #region Serialization conditions

    // should SomeInfo be serialized?
    public bool ShouldSerializeSomeInfo()
    {
         return SomeInfo != null; // serialize if not null
    }

    // should SomeOtherInfo be serialized?
    public bool ShouldSerializeSomeOtherInfo()
    {
         return SomeOtherInfo != null; // serialize if not null
    }

    #endregion
}
vgru
  • 49,838
  • 16
  • 120
  • 201
1

You can use XmlAttributeOverrides and overide the XmlIgnore attribute for your property.

(there is an example in the XmlIgnore msdn page)

manji
  • 47,442
  • 5
  • 96
  • 103