Wednesday, 24 April 2013

How to Use XmlAttribute with a Nullable Type?

Imagine you have the below property which should be serialized as an xml attribute if it has value and if not, it should just be ignored from the serialization:
[XmlAttribute("lastUpdated")]
public DateTime? LastUpdated { get; set; }
The solution would be introducing a new property and a new method:
 [XmlIgnore]
        public DateTime? LastUpdated { get; set; }

        [XmlAttribute("lastUpdated")]
        public DateTime LastUpdatedSerializable
        {
            get { return this.LastUpdated.Value; }
            set { this.LastUpdated = value; }
        }

        public bool ShouldSerializeLastUpdatedSerializable()
        {
            return LastUpdated.HasValue;
        }
It's important to know that ShouldSerialize{Property} and {Property}Specified are .NET Conventions to resolve this issue. I liked to find a better/cleaner/simpler approach but haven't found any yet.

No comments: