I needed to create an xml fragment that had optional elements that was serialized from a class. The optional elements were integers and decimals, types that are not nullable by default in .NET. Well, we can wrap those types in Nullable<T> and then add an another ignored property that helps out the .NET serializer.
[XmlElement(Order = 10)]public decimal? Height{ get { return height; } set { height = value; }}
[XmlIgnore]public bool HeightSpecified{ get { return height.HasValue; }}
With the additional HeightSpecified property, the XmlSerializer will only write out the Height property element if its non-null.
Initially I tried using [XmlElement(IsNullable=false)] on the Height property, but that ended up throwing an InvalidOperationException when I went to serialize my class.
Powered by: newtelligence dasBlog 2.1.8102.813
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2012, Shawn Neal
E-mail