Can I specify XMLRoot via code instead of attributes?

c#, xml-serialization

Solution

Yes! Simply:

var serializer = new XmlSerializer(typeof(MyRoot),
    new XmlRootAttribute("data"));

Or more completely, see `XmlAttributeOverrides`. However, with either of these you must cache and reuse the serializer instance, otherwise you'll leak assemblies.

Problem

Is there a way to set the xmlroot of an object or class during runtime? ``` [XmlRoot("data")] public class MyRoot { [XmlElement("bar")] public List<RemoteHost> Hosts {get;set;} } ``` I don't have the option of modifying the class MyRoot in this case; so, I would like to specify that I want the root name to be called "data" before I serialize the object to XML using XmlSerializer.

Original source