Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I specify XMLRoot via code instead of attributes?

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.

like image 241
Abe Avatar asked Oct 04 '12 22:10

Abe


1 Answers

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.

like image 183
Marc Gravell Avatar answered Nov 11 '22 00:11

Marc Gravell