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
Release: 2025-01-11 09:27:43
Original
575 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template