XML序列化节点错误地将其作为父类而不是子类

时间:2018-09-26 15:29:44

标签: c# serialization xml-serialization

我正在序列化一个错误地创建其属性之一的节点的类。我的课程结构如下:

这是我要序列化的顶级课程

    [DataContract]
    public class XmlReportConfiguration
    {
        [DataMember]
        [XmlArrayItem(nameof(SingleValueDescription), typeof(SingleValueDescription))]
        [XmlArrayItem(nameof(MultiValueDescription), typeof(MultiValueDescription))]
        public List<Description> Descriptions { get; set; }
    }

MultiValueDescription继承自SingleValueDescription,而SingleValueDescription继承自Description。

说明具有XMlInclude标记,用于单值和多值说明

我的问题是,当我要序列化MultiValueDescription类型的Description时,xml节点将其序列化为SingleValueDescription。

如果我从XmlReportConfiguration类中删除了SingleValueDescription的XmlArrayItem条目,则它可以按我希望的方式工作,但是出于明显的原因,我无法删除该声明。

这里是否缺少一些标记/声明,导致序列化程序忽略该节点的子类并使用父类?

以下是创建序列化程序的方法:

    public static string SerializeReportConfiguration(XmlReportConfiguration config)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(XmlReportConfiguration));
        StringBuilder sb = new StringBuilder();

        using (TextWriter writer = new StringWriter(sb))
        {
            serializer.Serialize(writer, config);
        }

        return sb.ToString();
    }


    public static XmlReportConfiguration DeserializeReportConfiguration(string xml)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(XmlReportConfiguration));
        using (StringReader reader = new StringReader(xml))
        {
            XmlReportConfiguration sessionConfig = serializer.Deserialize(reader) as XmlReportConfiguration;
            return sessionConfig;
        }
    }

1 个答案:

答案 0 :(得分:0)

找到了解决方案。多态性导致序列化时出现问题。在我的报告配置中,我使用了以下新类的列表,它解决了我的问题。

[DataContract]
public class SerializableDescription : IXmlSerializable
{
    #region Properties

    public SerializableDescription()
    {

    }

    public SerializableDescription(Description description)
    {
        Description = description;
    }

    [DataMember]
    public Description Description { get; set; }

    #endregion

    #region Methods

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        reader.MoveToContent();
        string typeStr = reader.GetAttribute("Type");
        Type type = TypeCache.GetTypeEx(typeStr);
        XmlSerializer ser = new XmlSerializer(type);
        reader.ReadStartElement();
        Description = (Description)ser.Deserialize(reader);
        reader.ReadEndElement();
    }

    public void WriteXml(XmlWriter writer)
    {
        Type type = Description.GetType();
        writer.WriteAttributeString("Type", type.FullName);
        XmlSerializer ser = new XmlSerializer(type);
        ser.Serialize(writer, Description);
    }

    #endregion
}