【问题标题】:Using XmlSerializer to serialize derived classes使用 XmlSerializer 序列化派生类
【发布时间】:2009-10-29 11:41:55
【问题描述】:

我正在使用 XMLSerializer 序列化包含通用列表的对象

List <ChildBase> Children {get;set}

问题是每个元素都派生自ChildBase,它实际上是一个抽象类。 当我尝试反序列化时,我得到一个 invalidOperationException

有没有办法可以将 XMLSerializer 与派生对象一起使用? 谢谢。

【问题讨论】:

    标签: c# xml-serialization


    【解决方案1】:

    有三种方法可以做到这一点;您可以对类型使用[XmlInclude],也可以对属性使用XmlElement/XmlArrayItem。它们都显示在下面;取消注释您喜欢的一对:

    using System;
    using System.Collections.Generic;
    using System.Xml.Serialization;
    public class MyWrapper {
        //2: [XmlElement("A", Type = typeof(ChildA))]
        //2: [XmlElement("B", Type = typeof(ChildB))]
        //3: [XmlArrayItem("A", Type = typeof(ChildA))]
        //3: [XmlArrayItem("B", Type = typeof(ChildB))]
        public List<ChildClass> Data { get; set; }
    }
    //1: [XmlInclude(typeof(ChildA))]
    //1: [XmlInclude(typeof(ChildB))]
    public abstract class ChildClass {
        public string ChildProp { get; set; }
    }
    public class ChildA : ChildClass {
        public string AProp { get; set; }
    }
    public class ChildB : ChildClass {
        public string BProp { get; set; }
    }
    static class Program {
        static void Main() {
            var ser = new XmlSerializer(typeof(MyWrapper));
            var obj = new MyWrapper {
                Data = new List<ChildClass> {
                    new ChildA { ChildProp = "abc", AProp = "def"},
                    new ChildB { ChildProp = "ghi", BProp = "jkl"}}
            };
            ser.Serialize(Console.Out, obj);
        }
    }
    

    【讨论】:

    • 现在尝试应用这个:[XmlRoot(ElementName = "myWrapper", Namespace = "URL/")]public class MyWrapper
    • 请注意,方法 1 似乎不适用于反序列化集合。反序列化器需要方法2或方法3来弄清楚如何将xml中的节点映射回集合中的项目。
    【解决方案2】:

    您可以为此使用XmlIncludeAttribute。或者查看this 发布的另一种方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多