2

My class

    public MyClass
    {
       [DataMemberAttribute(EmitDefaultValue = true)]
       public decimal? a { get; set; }
       [DataMemberAttribute(EmitDefaultValue = true)]
       public DateTime? b { get; set; }
       [DataMemberAttribute(EmitDefaultValue = true)]
       public int? c { get; set; }
       [DataMemberAttribute(EmitDefaultValue = true)]
       public bool? d { get; set; }
    }

Decimal, DateTime and int are nullable. So I have :

<MyClass ...>
    <a>3</a>
    <b i:nil="true"/>
    <c i:nil="true"/>
    <d i:nil="true"/>
</MyClass>

And when a, b, c will be null I want to get this :

<MyClass ...>
    <a>3</a>
    <b/>
    <c/>
    <d/>
</MyClass>
KingMaker
  • 83
  • 1
  • 1
  • 13

2 Answers2

0

you just need to create properties as below for each element that you want:

 public MyClass
    {

    [System.Xml.Serialization.XmlElement("b",IsNullable = false)]
        public object b
        {
            get
            {
                return b;
            }
            set
            {
                if (value == null)
                {
                    b = null;
                }
                else if (value is DateTime || value is DateTime?)
                {
                    b = (DateTime)value;
                }
                else
                {
                    b = DateTime.Parse(value.ToString());
                }
            }
        }

 //public object b ....

}
Niraj
  • 775
  • 7
  • 20
0

I did this finally :

XmlSerializer.SerializeToWriter(data, strw);
XDocument xdoc = XDocument.Load("myxmlfile.xml");

foreach (var attribute in xdoc.Descendants())
{
     if (attribute.FirstAttribute != null && attribute.FirstAttribute.ToString().Contains("i:nil"))
            attribute.FirstAttribute.Remove();
}
xdoc.Save("myxmlfile.xml");

And in my class I have

[DataMemberAttribute(EmitDefaultValue = true)]

So when it's null, it generate 'i:nil="true"', then I just have to remove it.

KingMaker
  • 83
  • 1
  • 1
  • 13