When a class is inherited from List<>, XmlSerializer doesn't serialize other attributes

前端 未结 2 1579
梦毁少年i
梦毁少年i 2020-11-27 07:45

I\'m having a situation here, I need my class to be inherited from List, but when I do this XmlSerializer does not serialize any property or fie

相关标签:
2条回答
  • 2020-11-27 08:30

    Here's a though for you to consider.

    You can have a class that is a container class like this:

    class ContainerObject
    {
         public int MyNewProperty { get; set; }
    
         [XmlElement("")]
         public List<int> MyList { get; set; }
    }
    

    The trick is to have XmlElement name = "" above the List element.

    When this is serialized into xml, you will have:

    <ContainerObject>
       <MyNewProperty>...</MyNewProperty>
    
       <int>...</int>
       <int>...</int>
    
    </ContainerObject>
    

    If you like, you can also create another class for items in a list

     class MyItem
     {
         public int MyProperty {get;set;} 
    
     } 
    

    and then instead of having List of ints, have a List of MyItems.

    This was you control XmlElement name of every item in a list.

    I hope this was helpful.

    0 讨论(0)
  • 2020-11-27 08:39

    This is by design. I don't know why this decision was made, but it is stated in the documentation:

    • Classes that implement ICollection or IEnumerable. Only collections are serialized, not public properties.

    (Look under "Items that can be serialized" section). Someone has filed a bug against this, but it won't be changed - here, Microsoft also confirms that not including the properties for classes implementing ICollection is in fact the behaviour of XmlSerializer.

    A workaround would be to either:

    • Implement IXmlSerializable and control serialization yourself.

    or

    • Change MyClass so it has a public property of type List (and don't subclass it).

    or

    • Use DataContractSerializer, which handles this scenario.
    0 讨论(0)
提交回复
热议问题