动态地将基类的集合序列化为XML

本文关键字:序列化 XML 集合 基类 动态 | 更新日期: 2023-09-27 17:57:56

O hai there,

我想序列化和对象,它看起来像这样:

public class Wrapper
{
    [XmlArray("Entities"), XmlArrayItem("Entity")]
    public List<Base> Entities { get; set; }
}

我想让应用程序尽可能灵活,因此在XmlArrayItem属性中手动设置派生类类型不是一个选项,我如何动态地做到这一点,即让序列化程序知道所有派生类。

顺便说一句,我已经有了一个类来获取所有直接派生的类型,比如BaseDerived.DerivedClassesXmlSerializer cs = new XmlSerializer(this.GetType(),BaseDerived.DerivedClasses);,它们不起作用。。。

知道吗?

动态地将基类的集合序列化为XML

找到一个灵魂,在序列化过程中,你几乎可以直接插入项目属性

所以首先你要收集这样的属性

    XmlAttributeOverrides xOver = new XmlAttributeOverrides();
    XmlAttributes xAttrs = new XmlAttributes();
    foreach (var cls in BaseDerived.DerivedClasses)
    {
        var attr = new XmlArrayItemAttribute(cls);
        xAttrs.XmlArrayItems.Add(attr);
    }
    xOver.Add(this.GetType(), BaseDerived.GetMemberName((Wrapper x) => x.Entities), xAttrs);

Btw:

public static string GetMemberName<T, TValue>(Expression<Func<T, TValue>> memberAccess)
{
    return ((MemberExpression)memberAccess.Body).Member.Name;
}

然后你只在序列化中提到它:

    XmlSerializer cs = new XmlSerializer(this.GetType(), xOver);
相关文章: