# Friday, May 16, 2008
« VS 2008 Web Settings | Main | Checking IIS Version From MSBuild »

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. 

Friday, May 16, 2008 5:55:11 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
Comments are closed.