.NET Serialization Ordering

后端 未结 6 899
故里飘歌
故里飘歌 2020-12-03 07:40

I am trying to serialize some objects using XmlSerializer and inheritance but I am having some problems with ordering the outcome.

Below is an example similar to wha

6条回答
  •  北海茫月
    2020-12-03 08:42

    I know this question has expired; however, here is a solution for this problem:

    The name of the method should always begin with ShouldSerialize and then end with the property name. Then you simply need to return a boolean based on whatever conditional you want, as to whether to serialize the value or not.

    public class SerializableBase
    {
        public bool Property1 { get; set;}
        public bool Property2 { get; set;}
        public bool Property3 { get; set;}
    
        public virtual bool ShouldSerializeProperty2 { get { return false; } }
    }
    
    [XmlRoot("Object")]
    public class SerializableObject1 : SerializableBase
    {        
    }
    
    [XmlRoot("Object")]
    public class SerializableObject2 : SerializableBase
    {
        public override bool ShouldSerializeProperty2 { get { return true; } }
    }
    

    The outcome when using SerializableObject2: ~

    
        
        
        
    
    

    The outcome when using SerializableObject1: ~

    
        
        
    
    

    Hope this helps many others!

提交回复
热议问题