XML Serialization similar to what Json.Net can do XML Serialization similar to what Json.Net can do xml xml

XML Serialization similar to what Json.Net can do


You don't need to pollute your models with XmlInclude attributes. You could explicitly indicate all known classes to the XmlSerializer's constructor:

var serializer = new XmlSerializer(obj.GetType(), new[] { typeof(Bar) });

Also using object as base class seems like a crappy approach. At least define a marker interface:

public interface IMarker{}

that your Bar's will implement:

public class Bar : IMarker{    public int Arg1 { get; set; }    public double Arg2 { get; set; }}

and then then specialize the Value1 property of your Foo class to this marker instead of making it like the most universal type in the universe (it can't be):

public class Foo{    public IMarker Value1 { get; set; }    public string Value2 { get; set; }}

Coz now it's pretty trivial to get all loaded types at runtime in all referenced assemblies that are implementing the marker interface and passing them to the XmlSerializer constructor:

var type = typeof(IMarker);var types = AppDomain.CurrentDomain.GetAssemblies()    .SelectMany(s => s.GetTypes())    .Where(p != type)    .Where(p => type.IsAssignableFrom(p))    .ToArray();var serializer = new XmlSerializer(obj.GetType(), types);

Now you've got a pretty capable XmlSerializer that will know how to properly serialize all types implementing your marker interface. You've achieved almost the same functionality as JSON.NET. And don't forget that this XmlSerializaer instantiation should reside in your Composition Root project which knows about all loaded types.

And once again using object is a poor design decision.