0

I have object which I am trying to serialise. There is one property that can sometimes be null which is causing me issues.

The issue is that once my object has been serialised looking at the XML message I see the line below.

<CostAmount d3p1:nil="true" xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" />

What I would like is the tag CostAmount to not be included in the message at all.

I have been tried the example c# xml serialization doesn't write null but it didn't work for me.

Edit

Below is the property mentioned above. I should mention that the this is a partial class. This partial class was made by myself. Entity framework made the other partial class. I can see an issue now being that entity framework auto generate the get & set.

        [XmlElement("dfCostAmount")]
        public Double? CostAmount;
        [XmlIgnore]
        public bool CostAmountSpecified
        {
            get
            {
                return (CostAmount != null & CostAmount.HasValue);
            }
        }
Community
  • 1
  • 1
mHelpMe
  • 6,336
  • 24
  • 75
  • 150

1 Answers1

1

You can implement a member following the ShouldSerialize pattern. Similar to your code above but instead of CostAmountSpecified property you implement the member ShouldSerializeCostAmount.

Example:

public bool ShouldSerializeCostAmount()
{
   return CostAmount.HasValue;      
}
  • Hi Neill I actually tried the ShouldSerialize pattern first and that didn't work either. I think the issue is to do with entity framework auto generating the get & setters. – mHelpMe Oct 31 '13 at 14:56