31 August 2006

Serializing nullable XML attributes...

Well, again this may be obvious to a lot of people, but I thought it was worth a post here.

The other day I was working on a project where some data needed to be serialized into XML using the XmlSerializer.
Some of the classes that needed to be serialized had some GUID's for identifiers, which intuitively becomes a XML attribute in my world, as with all identifiers.
However, some of the identifiers could in some cases be null, which normally wouldn't be possible in .NET 1.1 (you could of course use Guid.Empty but it's not very neat), but in 2.0 there is the Nullable class, which in this situation came quite in handy.

Now, take a look at the following:
private Guid? sysId;
private Guid? traceId;


[XmlAttribute()]
public Guid? SysId
{
get{ return this.sysId; }
set{ this.sysId = value; }
}


[XmlAttribute()]
public Guid? TraceId
{
get{ return this.traceId; }
set{ this.traceId = value; }
}
Trying to serialize the code above will throw one of those completely useless XML serialization exceptions, which you can use hours trying to debug.
But the question is why?
Well, the reason is quite simple. Serializing a nullable valuetype into XML results in the following:

<FooBar xsi:nil="true" />

The above does not exactly adhere to a wellformed XML attribute, and the result would look something like this:

<XmlElement attribute1="foo" FooBar xsi:nil="true" />

So there it is.
The way the .NET Framework serializes it's nullable types does not work well with XML attributes, so either you have to live with it and let the property be an XML element, or you have to make up your own serialization mechanisms taking care of the nullable types in a custom way.

No comments: