Archive for July, 2009
c# Getting a nullable attribute to serialize to xml
by brian on Jul.23, 2009, under .NET, c#, c# coding GUI, coding, linq
It isn’t straight forward to get a nullable field to serialize. Technically it isn’t supported. But I just discovered a way today. You see null strings are supported. The idea is to ignore the real nullable property while substituting the string version as follows:
[XmlRoot("Comment")]
public class Comment
{
[XmlIgnore]
public DateTime? CommentTime { get; set; }
[XmlAttribute("CommentTime")]
public string CommentTimeStr
{
get
{
return (CommentTime.HasValue) ? CommentTime.Value.ToString() : null;
}
set
{
if (string.IsNullOrEmpty(value))
CommentTime = null;
else
CommentTime = DateTime.Parse(value);
}
}
}
Now it can be serialized.
