Bee Eee Blog

c# Getting a nullable attribute to serialize to xml

by 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.

No comments for this entry yet...

Comments are closed.

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...