2

Do anyone know how programatically add an [XmlIgnore] attribute to a class property in c#?

I'd like to do this to have just one class with one or two fields to be serialized as I'd need at run time.

Many thanks in advance.

Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
user3244672
  • 27
  • 1
  • 5

1 Answers1

10

It is possible to dynamically override XML serialization attributes by passing XmlAttributeOverrides object to XmlSerializer constructor.

XmlAttributes samplePropertyAttributes = new XmlAttributes();
samplePropertyAttributes.XmlIgnore = true;

XmlAttributeOverrides sampleClassAttributes = new XmlAttributeOverrides();
sampleClassAttributes.Add(typeof(SampleClass), "SampleProperty", samplePropertyAttributes);

var serializer = new XmlSerialized(typeof(SampleClass), sampleClassAttributes);

See XmlAttributeOverrides Class in MSDN for details.

PashaPash
  • 1,972
  • 15
  • 38
  • Yeah! Implemented 'n' tested: it works! – user3244672 Jan 28 '14 at 15:05
  • 1
    Also note that the XmlSerializer(Type, XmlAttributeOverrides) constructor dynamically creates an assembly during runtime and doesn't cache it! So each call to this constructor will create another assembly which could lead to memory leaks. XmlSerializer is thread safe so if you are going to use this constructor, it's best to cache the XmlSerializer you created – Sal Jun 24 '15 at 10:50