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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With