序列化一个继承自classA的对象列表到xml,所以xml中的元素名称分别为B,C,D

Serialize a list of objects inheriting from class A to xml, so the names of the elements in the xml are B,C,D

使用 DataContractSerializer 我想序列化从 class A 继承的对象列表。这些对象在不同的​​程序集中,假设它们属于 class B、C 和D. 我已将 B、C 和 D 添加到数据协定序列化程序的已知类型中。我能够序列化列表,但序列化的结果如下所示:

<SerializedListObjects>
   <A i:type="B">
   <A i:type="C">
</SerializedListObjects>

我想要的是:

<SerializedListObjects>
   <B>
   <C>
</SerializedListObjects>

可能在 B 和 C 中可以有一些属性具有从 A 继承的信息。

这是我的基地class:

  [Serializable]
  [DataContract(Name = "A")]
  public abstract class A
  {
  }

这是派生的 class 定义的示例。

  [Serializable]
  [DataContract(Name = "B")]
  public class B : A
  {
  }

由于派生的 classes 在不同的程序集中,我不能在它们的基础 class 或包含派生的 class 的序列化 class 中放置任何属性37=] 名称(例如 [XmlElement("B", Type = typeof(ChildB))])- 我无权访问那里的派生 classes。

可能吗?

虽然我目前正在使用 DataContractSerializer,但我愿意在必要时切换到另一个 XML 序列化程序,例如 XmlSerializer

首先,DataContractSerializer 没有通过更改集合元素名称来支持集合项多态性的机制。它仅支持 known type mechanism which uses the i:type 属性 - 您指出该属性是不可接受的。

既然您愿意切换到 XmlSerializer,您可以使用属性 XmlArrayItemAttribute.Type 来指定列表中多态类型的元素名称:

public class AListObject
{
    [XmlArrayItem(typeof(B))]
    [XmlArrayItem(typeof(C))]
    public List<A> SerializedListObjects { get; set; }
}

但是,您还指出不能在编译类型中静态声明多态子类型,因为它们存在于其他一些程序集中。

因此,您将需要使用 XmlAttributeOverrides mechanism to specify all possible derived types for all List<A> properties in runtime, and manually construct an XmlSerializer 使用这些覆盖。

这是一个原型解决方案。首先,假设您有一个根对象,它引用一个包含 List<A> 的对象,如下所示:

public class RootObject
{
    public AListObject AList { get; set; }
}

public class AListObject
{
    public List<A> SerializedListObjects { get; set; }
}

(根对象可以是带有 List<A> 属性 的对象,但不一定是。)我们还假设您知道所有此类对象,例如 AListObject可能包含 List<A> 属性。

根据这些假设,以下序列化器工厂可用于为任何可能引用包含 List<A> 属性 的已知类型的任何实例的任何根对象生成 XmlSerializer :

public interface IXmlSerializerFactory
{
    XmlSerializer CreateSerializer(Type rootType);
}

public static class AListSerializerFactory
{
    static readonly XmlArrayItemTypeOverrideSerializerFactory instance;

    static AListSerializerFactory()
    {
        // Include here a list of all types that have a List<A> property.
        // You could use reflection to find all such public types in your assemblies.
        var declaringTypeList = new []
        {
            typeof(AListObject),
        };

        // Include here a list of all base types with a corresponding mapping 
        // to find all derived types in runtime.   Here you could use reflection
        // to find all such types in your assemblies, as shown in 
        // 
        var derivedTypesList = new Dictionary<Type,  Func<IEnumerable<Type>>>
        {
            { typeof(A), () => new [] { typeof(B), typeof(C) } },
        };
        instance = new XmlArrayItemTypeOverrideSerializerFactory(declaringTypeList, derivedTypesList);
    }

    public static IXmlSerializerFactory Instance { get { return instance; } }
}

public class XmlArrayItemTypeOverrideSerializerFactory : IXmlSerializerFactory
{
    // To avoid a memory & resource leak, the serializers must be cached as explained in
    // 

    readonly object padlock = new object();
    readonly Dictionary<Type, XmlSerializer> serializers = new Dictionary<Type, XmlSerializer>();
    readonly XmlAttributeOverrides overrides;

    public XmlArrayItemTypeOverrideSerializerFactory(IEnumerable<Type> declaringTypeList, IEnumerable<KeyValuePair<Type, Func<IEnumerable<Type>>>> derivedTypesList)
    {
        var completed = new HashSet<Type>();
        overrides = declaringTypeList
            .SelectMany(d => derivedTypesList.Select(p => new { declaringType = d, itemType = p.Key, derivedTypes = p.Value() }))
            .Aggregate(new XmlAttributeOverrides(), (a, d) => a.AddXmlArrayItemTypes(d.declaringType, d.itemType, d.derivedTypes, completed));
    }

    public XmlSerializer CreateSerializer(Type rootType)
    {
        lock (padlock)
        {
            XmlSerializer serializer;
            if (!serializers.TryGetValue(rootType, out serializer))
                serializers[rootType] = serializer = new XmlSerializer(rootType, overrides);
            return serializer;
        }
    }
}

public static partial class XmlAttributeOverridesExtensions
{
    public static XmlAttributeOverrides AddXmlArrayItemTypes(this XmlAttributeOverrides overrides, Type declaringType, Type itemType, IEnumerable<Type> derivedTypes)
    {
        return overrides.AddXmlArrayItemTypes(declaringType, itemType, derivedTypes, new HashSet<Type>());
    }

    public static XmlAttributeOverrides AddXmlArrayItemTypes(this XmlAttributeOverrides overrides, Type declaringType, Type itemType, IEnumerable<Type> derivedTypes, HashSet<Type> completedTypes)
    {
        if (overrides == null || declaringType == null || itemType == null || derivedTypes == null || completedTypes == null)
            throw new ArgumentNullException();
        XmlAttributes attributes = null;
        for (; declaringType != null && declaringType != typeof(object); declaringType = declaringType.BaseType)
        {
            // Avoid duplicate overrides.
            if (!completedTypes.Add(declaringType))
                break;
            foreach (var property in declaringType.GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance))
            {
                // Skip the property if already ignored
                if (property.IsDefined(typeof(XmlIgnoreAttribute), false))
                    continue;

                // See if it is a list property, and if so, get its type.
                var propertyItemType = property.PropertyType.GetListType();
                if (propertyItemType == null)
                    continue;

                // OK, its a List<itemType>.  Add all the necessary XmlElementAttribute declarations.
                if (propertyItemType == itemType)
                {
                    if (attributes == null)
                    {
                        attributes = new XmlAttributes();
                        foreach (var derivedType in derivedTypes)
                            // Here we are assuming all the derived types have unique XML type names.
                            attributes.XmlArrayItems.Add(new XmlArrayItemAttribute { Type = derivedType });
                        if (itemType.IsConcreteType())
                            attributes.XmlArrayItems.Add(new XmlArrayItemAttribute { Type = itemType });
                    }
                    overrides.Add(declaringType, property.Name, attributes);
                }
            }
        }
        return overrides;
    }
}

public static class TypeExtensions
{
    public static bool IsConcreteType(this Type type)
    {
        return !type.IsAbstract && !type.IsInterface;
    }

    public static Type GetListType(this Type type)
    {
        while (type != null)
        {
            if (type.IsGenericType)
            {
                var genType = type.GetGenericTypeDefinition();
                if (genType == typeof(List<>))
                    return type.GetGenericArguments()[0];
            }
            type = type.BaseType;
        }
        return null;
    }
}

然后,您可以将 RootObject 的实例序列化和反序列化为 XML,如下所示:

var root = new RootObject
{
    AList = new AListObject
    {
        SerializedListObjects = new List<A> { new B(), new C() },
    },
};

var serializer = AListSerializerFactory.Instance.CreateSerializer(root.GetType());

var xml = root.GetXml(serializer);
var root2 = xml.LoadFromXml<RootObject>(serializer);

使用扩展方法:

public static class XmlSerializationHelper
{
    public static T LoadFromXml<T>(this string xmlString, XmlSerializer serial = null)
    {
        serial = serial ?? new XmlSerializer(typeof(T));
        using (var reader = new StringReader(xmlString))
        {
            return (T)serial.Deserialize(reader);
        }
    }

    public static string GetXml<T>(this T obj, XmlSerializer serializer = null)
    {
        using (var textWriter = new StringWriter())
        {
            var settings = new XmlWriterSettings() { Indent = true }; // For cosmetic purposes.
            using (var xmlWriter = XmlWriter.Create(textWriter, settings))
                (serializer ?? new XmlSerializer(obj.GetType())).Serialize(xmlWriter, obj);
            return textWriter.ToString();
        }
    }
}

结果是:

<RootObject xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <AList>
    <SerializedListObjects>
      <B />
      <C />
    </SerializedListObjects>
  </AList>
</RootObject>

备注:

  • 中所述,Memory Leak using StreamReader and XmlSerializer, you must statically cache any XmlSerializer constructed with XmlAttributeOverrides to avoid a severe memory leak. The documentation 建议使用 Hashtable,但是 XmlAttributeOverrides 不会覆盖 Equals()GetHashCode(),并且没有为应用程序开发人员编写自己的内部数据提供足够的访问权限。因此,每当使用 XmlAttributeOverrides 时,有必要手工制作某种静态缓存方案。

  • 鉴于查找和覆盖所有 List<A> 属性的 XmlArrayItem 特性的复杂性,您可能会考虑坚持使用现有的 i:type 机制。它很简单,效果很好,DataContractSerializerXmlSerializer, and is standard 都支持。

  • 我用通用的方式写了 class XmlArrayItemTypeOverrideSerializerFactory,这增加了表面上的复杂性。

工作示例 .Net fiddle here.