Home >Backend Development >C++ >How to Serialize Derived Classes in Generic Lists with XmlSerializer?
When using XmlSerializer for XML serialization, you may encounter challenges when handling objects containing generic lists derived from abstract classes. Attempts to deserialize such objects may result in an InvalidOperationException.
To resolve this issue, you can use one of the following three methods:
1. Use the [XmlInclude] attribute on the base type:
<code class="language-csharp">using System.Xml.Serialization; [XmlInclude(typeof(ChildA))] [XmlInclude(typeof(ChildB))] public abstract class ChildClass { public string ChildProp { get; set; } }</code>
2. Use the [XmlElement] attribute on the attribute:
<code class="language-csharp">public class MyWrapper { [XmlElement("A", Type = typeof(ChildA))] [XmlElement("B", Type = typeof(ChildB))] public List<ChildClass> Data { get; set; } }</code>
3. Use the [XmlArrayItem] attribute on the attribute:
<code class="language-csharp">public class MyWrapper { [XmlArrayItem("A", Type = typeof(ChildA))] [XmlArrayItem("B", Type = typeof(ChildB))] public List<ChildClass> Data { get; set; } }</code>
Uncomment the corresponding attribute pairs according to your specific needs. By using one of these methods, XmlSerializer will be able to handle derived classes during serialization and deserialization.
The above is the detailed content of How to Serialize Derived Classes in Generic Lists with XmlSerializer?. For more information, please follow other related articles on the PHP Chinese website!