Search code examples
c#wcfserializationdatacontractserializerxmlserializer

Lost attributes in serialization List<> inherited class


I am using WCF. I have the following model classes. When the object serialization list cIntList property Name is lost. I found the answer here: When a class is inherited from List<>, XmlSerializer doesn't serialize other attributes. However, important to me not to build a container class only modify the same serialization. Can anyone help me modify the class so as to allow its serialization in line with my expectations?

   public class IntData
    {
        public int Value;
        public IntData()
        {
        }
    }

    public class cIntList : List<IntData>
    {
        public string Name;

        public cIntList()
        {
            Name = "Name";
            this.Add(new IntData() { Value = 1 });
            this.Add(new IntData() { Value = 2 });
        }
    }

Solution

  • If you change the class it will serialize the name field too.

    public class cIntList
    {
        public string Name{ get; set; }
    
        [XmlElement("")]
        public List<IntData> IntList{ get; set; }
    
        public cIntList()
        {
            Name = "Name";
            IntList = new List<IntData>();
            IntList.Add(new IntData() { Value = 1 });
            IntList.Add(new IntData() { Value = 2 });
        }
    }
    

    You can change or remove the XmlElement attribute depending on your desired xml.