At runtime, you can override serialization attributes. Here is an example:
class Program
{
static void Main(string[] args)
{
XmlSerializer ser = new XmlSerializer(typeof(Foo));
Foo foo1 = (Foo)ser.Deserialize(XmlReader.Create(@"..\..\XMLFile1.xml"));
Console.WriteLine(foo1.Bar);
XmlRootAttribute newRoot = new XmlRootAttribute();
newRoot.ElementName = "Root";
newRoot.Namespace = "http://example.org/";
XmlAttributes myAttributes = new XmlAttributes();
myAttributes.XmlRoot = newRoot;
XmlAttributeOverrides myOverrides = new XmlAttributeOverrides();
myOverrides.Add(typeof(Foo), myAttributes);
ser = new XmlSerializer(typeof(Foo), myOverrides);
Foo foo2 = (Foo)ser.Deserialize(XmlReader.Create(@"..\..\XMLFile2.xml"));
Console.WriteLine(foo2.Bar);
}
}
[XmlRoot(ElementName="Root", Namespace="http://example.com/")]
public class Foo
{
public string Bar { get; set; }
}
The first deserialization consumes
<?xml version="1.0" encoding="utf-8" ?>
<Root xmlns="http://example.com/">
<Bar>Baz</Bar>
</Root>
the second
<?xml version="1.0" encoding="utf-8" ?>
<Root xmlns="http://example.org/">
<Bar>Baz</Bar>
</Root>
class Program
{
static void Main(string[] args)
{
XmlSerializer ser = new XmlSerializer(typeof(Foo));
Foo foo1 = (Foo)ser.Deserialize(XmlReader.Create(@"..\..\XMLFile1.xml"));
Console.WriteLine(foo1.Bar);
XmlRootAttribute newRoot = new XmlRootAttribute();
newRoot.ElementName = "Root";
newRoot.Namespace = "http://example.org/";
XmlAttributes myAttributes = new XmlAttributes();
myAttributes.XmlRoot = newRoot;
XmlAttributeOverrides myOverrides = new XmlAttributeOverrides();
myOverrides.Add(typeof(Foo), myAttributes);
ser = new XmlSerializer(typeof(Foo), myOverrides);
Foo foo2 = (Foo)ser.Deserialize(XmlReader.Create(@"..\..\XMLFile2.xml"));
Console.WriteLine(foo2.Bar);
}
}
[XmlRoot(ElementName="Root", Namespace="http://example.com/")]
public class Foo
{
public string Bar { get; set; }
}
The first deserialization consumes
<?xml version="1.0" encoding="utf-8" ?>
<Root xmlns="http://example.com/">
<Bar>Baz</Bar>
</Root>
the second
<?xml version="1.0" encoding="utf-8" ?>
<Root xmlns="http://example.org/">
<Bar>Baz</Bar>
</Root>