Home >Backend Development >C++ >How Can I Serialize Derived Classes Using XmlSerializer?

How Can I Serialize Derived Classes Using XmlSerializer?

DDD
DDDOriginal
2025-01-11 09:53:43139browse

How Can I Serialize Derived Classes Using XmlSerializer?

Use XmlSerializer to serialize derived classes

Developers may encounter an InvalidOperationException if using XmlSerializer when trying to serialize an object that contains an abstract class as part of its properties. Overcoming this obstacle requires efficient handling of derived classes during serialization.

Solution

XmlSerializer provides three methods to solve this problem:

  1. [XmlInclude] Attribute: Applied to the base class, it indicates that the serializer contains derived classes.

    <code class="language-csharp"> [XmlInclude(typeof(ChildA))]
     [XmlInclude(typeof(ChildB))]
     public abstract class ChildClass
     {
         public string ChildProp { get; set; }
     }</code>
  2. XmlElement/XmlArrayItem Attributes: These attributes should be applied to properties carrying lists, specifying the type of each derived class element.

    <code class="language-csharp"> [XmlElement("A", Type = typeof(ChildA))]
     [XmlElement("B", Type = typeof(ChildB))]
     public List<ChildClass> Data { get; set; }</code>
  3. XmlArrayItem Attributes: Placed on the list itself, they define the types of elements the list can contain.

    <code class="language-csharp"> [XmlArrayItem("A", Type = typeof(ChildA))]
     [XmlArrayItem("B", Type = typeof(ChildB))]
     public List<ChildClass> Data { get; set; }</code>

By selecting one of these options and uncommenting the corresponding code block in the provided code sample, developers can successfully serialize and deserialize objects containing derived classes.

The above is the detailed content of How Can I Serialize Derived Classes Using 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