February 01, 2008

XMLSerialization & null/empty elements

I recently ran into an issue where an application was serializing a .NET object and returning the XML, but not returning elements where the properties were null. The consuming client expected every element in the schema to be returned, so we needed to come up with the best way to generate XML containing all elements & nodes regardless of whether they contained data.

The first solution was to simply decorate the property with

[XmlElement(IsNullable=true)]

which makes sure the element is always generated. The resulting xml element contains the attribute xsi:nil="true" when it is null. That works just fine, but an even simpler solution is just to initialize the private variable behind the property to string.empty. That ensures that the property was always at least an empty string, rather than null. To the XmlSerializer, empty string means generate element. But if you require that the resulting XML has to include all properties, even true nulls, then decorating potentially null properties with the XmlElement IsNullable Attribute is the way to go.

Share |

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete