Home >Backend Development >C++ >How to Serialize Derived Classes in Generic Lists with XmlSerializer?

How to Serialize Derived Classes in Generic Lists with XmlSerializer?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-11 09:27:43527browse

How to Serialize Derived Classes in Generic Lists with XmlSerializer?

Use XmlSerializer to serialize derived classes

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn