XML序列化基类列表

本文关键字:列表 基类 序列化 XML | 更新日期: 2023-09-27 18:13:28

考虑下面的类结构

[XmlInclude(typeof(DerivedClass))]
public class BaseClass
{
    public string mem1;
    public string mem2;
}
public class DerivedClass : List<BaseClass>
{
    public string mem3;
    public string mem4;
}
class Program
{
    static void Main(string[] args)
    {
        DerivedClass obj = new DerivedClass();
        obj.mem3 = "test3";
        obj.mem4 = "test4";
        BaseClass base11 = new BaseClass();
        base11.mem1 = "test1";
        base11.mem2 = "test2";
        obj.Add(base11);
        XElement
           .Parse(XMLSerializerUtil.GetXMLFromObject(obj))
           .Save(@"C:'new_settings1.xml");
    }
}

GetXMLFromObject给出的代码如下

public static string GetXMLFromObject(object instance)
{
        string retVal = string.Empty;
        if (instance != null)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(instance.GetType());
            using (MemoryStream memoryStream = new MemoryStream())
            {
                xmlSerializer.Serialize(memoryStream, instance);
                memoryStream.Position = 0;
                retVal = new StreamReader(memoryStream).ReadToEnd();
            }
        }
        return retVal;
    }

即使在添加了XmlInclude属性之后,在生成的XML文件中,派生类成员也不存在。

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfBaseClass xmlns:xsd="http://www.w3.org/2001/XMLSchema"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <BaseClass>
        <mem1>test1</mem1>
        <mem2>test2</mem2>
    </BaseClass>
</ArrayOfBaseClass>

请让我知道,在生成的XML文件中包含派生类成员缺少什么

XML序列化基类列表

问题来了:

DerivedClass : List<BaseClass>

对于XmlSerializer,项要么是列表独占,要么是实体。如果它看起来像一个列表,那么只有列表项被序列化;"list"本身的成员不被序列化。基本上,不要那样做。不是从列表派生,而是封装一个列表:

同时,注意[XmlInclude(...)]期望DerivedClass : BaseClass。比如:

public class SomeType // note DOES NOT INHERIT
{
    private readonly List<SomeOtherType> items = new List<SomeOtherType>();
    public List<SomeOtherType> Items { get { return items; } }
    [XmlElement("mem3")] public string Mem3 {get;set;}
    [XmlElement("mem4")] public string Mem4 {get;set;}
}
public class SomeOtherType
{
    [XmlElement("mem1")] public string Mem1 {get;set;}
    [XmlElement("mem2")] public string Mem2 {get;set;}
}