The XmlSerializer allows you to specify attribute overrides
dynamically at runtime. Let's suppose that you have the following static class:
public class Foo
{
public string Bar { get; set; }
}
and the following XML:
<?xml version="1.0" encoding="utf-8" ?>
<foo bar="baz" />
you could dynamically add the mapping at runtime without using any static attributes on your model class. Just like this:
using System;
using System.Xml;
using System.Xml.Serialization;
public class Foo
{
public string Bar { get; set; }
}
class Program
{
static void Main()
{
var overrides = new XmlAttributeOverrides();
overrides.Add(typeof(Foo), new XmlAttributes { XmlRoot = new XmlRootAttribute("foo") });
overrides.Add(typeof(Foo), "Bar", new XmlAttributes { XmlAttribute = new XmlAttributeAttribute("bar") });
var serializer = new XmlSerializer(typeof(Foo), overrides);
using (var reader = XmlReader.Create("test.xml"))
{
var foo = (Foo)serializer.Deserialize(reader);
Console.WriteLine(foo.Bar);
}
}
}
Now all that's left for you is to write some custom code that might read an XML file containing the attribute overrides and building an instance of XmlAttributeOverrides
from it at runtime that you will feed to the XmlSerializer
constructor.