Can I dynamically apply XmlIgnore to properties of an ArrayItem?

后端 未结 1 1933
南旧
南旧 2021-01-16 04:08

I am trying to serialize a List where T: EntityObject and would love to leave out all the EntityKey and other EntityReference properties from the items in the list.

相关标签:
1条回答
  • 2021-01-16 04:33

    Yes you can do that - the main error is you need typeof(Car) instead of typeof(double). With this, note that XmlAttributeOverrides does not just apply to the top-level onject.

    However, I'm not sure that is the easiest route. Firstly, note that you must store and re-use the serialiser when using XmlAttributeOverrides otherwise you will leak assemblies.

    I expect the main reason you want to do this is because you don't want to edit he generated file. However, there is another way; in a separate file, in the right namespace, you can use:

    partial class Car {
        public bool ShouldSerializeEngineSize() { return false; }
    }
    

    Where "ShouldSerialize*" is a pattern recognised and used by XmlSerializer to control conditional serialization. The "partial" class is simply a way of combining two separate code files into a single type (and was designed for this generated-content scenario).

    This way, you dont need to mess with XmlAttributeOverrides, and you can use the simpler "new XmlSeralizer(Type)" (which has automatic caching per-type).

    0 讨论(0)
提交回复
热议问题