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
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 XmlElementAttribute
s 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.
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.
I'd use xpath to quickly figure out whether the input xml contains class A or class B. Then deserialize it based on that.