.NET Serialization Ordering

后端 未结 6 900
故里飘歌
故里飘歌 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:20

    This post is quite old now, but I had a similar problem in WCF recently, and found a solution similar to Steve Cooper's above, but one that does work, and presumably will work for XML Serialization too.

    If you remove the XmlElement attributes from the base class, and add a copy of each property with a different name to the derived classes that access the base value via the get/set, the copies can be serialized with the appropriate name assigned using an XmlElementAttribute, and will hopefully then serialize in the default order:

    public class SerializableBase
    {
       public bool Property1 { get; set;}
       public bool Property3 { get; set;}
    }
    
    [XmlRoot("Object")]
    public class SerializableObject : SerializableBase
    {
      [XmlElement("Property1")]
      public bool copyOfProperty1 
      { 
        get { return base.Property1; }
        set { base.Property1 = value; }
      }
    
      [XmlElement]
      public bool Property2 { get; set;}
    
      [XmlElement("Property3")]
      public bool copyOfProperty3
      { 
        get { return base.Property3; }
        set { base.Property3 = value; }
      }
    }
    

    I also added an Interface to add to the derived classes, so that the copies could be made mandatory:

    interface ISerializableObjectEnsureProperties
    {
      bool copyOfProperty1  { get; set; }
      bool copyOfProperty2  { get; set; }
    }
    

    This is not essential but means that I can check everything is implemented at compile time, rather than checking the resultant XML. I had originally made these abstract properties of SerializableBase, but these then serialize first (with the base class), which I now realise is logical.

    This is called in the usual way by changing one line above:

    public class SerializableObject : SerializableBase, ISerializableObjectEnsureProperties
    

    I've only tested this in WCF, and have ported the concept to XML Serialization without compiling, so if this doesn't work, apologies, but I would expect it to behave in the same way - I'm sure someone will let me know if not...

提交回复
热议问题