1

How to extend XmlAttribute class?

Using the below code, I've made my nullable property to be serializable and gets excluded from serialization if there is no value:

 [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;
        }

Instead of above, I'd like to be able to use the below code to achieve the same result:

        [XmlAttribute("lastUpdated", IsNullable = true)]
        public DateTime? LastUpdatedSerializable
        {
            get;
            set;
        }

Therefore, I'd like to be able to extend the XmlAttribute to accept a property called IsNullable then if the value is true, it should replace the implementation with the above codes so that if there is no value then the node be excluded.

It's something that Microsoft should have added to .NET Framework really for XmlAttribute.

How to achieve it?

The Light
  • 26,341
  • 62
  • 176
  • 258
  • An attribute only attaches Meta. Even if you added the `IsNullable` property, you will also need to change the serializer so that it implements logic to use the added property. – Myrtle Apr 24 '13 at 09:27
  • That's OK. As long as there can appear a less ugly implementation. – The Light Apr 24 '13 at 09:50
  • The `XmlAttributeAttribute` Class is not sealed. You can inherit from it, even name it the same in another namespace that you can import with the `Using` namespace. I doubt if this is a good approach. – Myrtle Apr 24 '13 at 09:55

0 Answers0