Custom Xml Serialization of Unknown Type

前端 未结 3 1511
失恋的感觉
失恋的感觉 2020-12-21 06:19

I\'m attempting to deserialize a custom class via the XmlSerializer and having a few problems, in the fact that I don\'t know the type that I\'m going to be deserializing (i

3条回答
  •  悲&欢浪女
    2020-12-21 07:00

    I don't think you need to implement IXmlSerializable...

    Since you don't know the actual types before runtime, you can dynamically add attribute overrides to the XmlSerializer. You just need to know the list of types that inherit from A. For instance, if you use A as a property of another class :

    public class SomeClass
    {
        public A SomeProperty { get; set; }
    }
    

    You can dynamically apply XmlElementAttributes for each derived type to that property :

    XmlAttributes attr = new XmlAttributes();
    var candidateTypes = from t in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
                         where typeof(A).IsAssignableFrom(t) && !t.IsAbstract
                         select t;
    foreach(Type t in candidateTypes)
    {
        attr.XmlElements.Add(new XmlElementAttribute(t.Name, t));
    }
    
    XmlAttributeOverrides overrides = new XmlAttributeOverrides();
    overrides.Add(typeof(SomeClass), "SomeProperty", attr);
    
    XmlSerializer xs = new XmlSerializer(typeof(SomeClass), overrides);
    ...
    

    This is just a very basic example, but it shows how to apply XML serialization attributes at runtime when you can't do it statically.

提交回复
热议问题