Last post Oct 27, 2016 12:50 PM by Siva Krishna Macha
Oct 27, 2016 12:32 PM|sudip_inn|LINK
based on some situation i want to include a property in xml serialization and some exclude that property. i know XmlIgnore help us to exclude property dynamically but how could i used it in such a way as a result based on some condition a property method
will be included in xml serialization and some time not. so please advise me how could i do it. thanks
Oct 27, 2016 12:50 PM|Siva Krishna Macha|LINK
XmlSerializer constructor accepts the second parameter to override the attributes.
You can pass in any overwrites in there.
See this documentation from MSDN for complete details:
In your specific case, as you are looking for XmlIgnore, following sample would be easier to understand:
XmlAttributes samplePropertyAttributes = new XmlAttributes();
samplePropertyAttributes.XmlIgnore = true;
XmlAttributeOverrides sampleClassAttributes = new XmlAttributeOverrides();
sampleClassAttributes.Add(typeof(SampleClass), "SampleProperty", samplePropertyAttributes);
var serializer = new XmlSerialized(typeof(SampleClass), sampleClassAttributes);
1st Reference: http://stackoverflow.com/a/21407983
Another example if you want to do more with XmlElement as well: http://stackoverflow.com/a/602404
However, I would advise to avoid such situation by sending the property as null or empty etc so you don't need to override the defaults because doing so would compromise on performance a bit, if you are working on a performance critical operations as the
serialization assembly will be generated every time and doesn't get cached and you might need to work on caching your serializer in such performance critical apps as per the comment mentioned in the first reference.