Custom Xml Serialization of Unknown Type

前端 未结 3 1492
失恋的感觉
失恋的感觉 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.

    0 讨论(0)
  • 2020-12-21 07:03

    To create an instance from a string, use one of the overloads of Activator.CreateInstance. To just get a type with that name, use Type.GetType.

    0 讨论(0)
  • 2020-12-21 07:10

    I'd use xpath to quickly figure out whether the input xml contains class A or class B. Then deserialize it based on that.

    0 讨论(0)
提交回复
热议问题