Thomas Kjørnes Thomas Kjørnes - 11 months ago 53
C# Question

How can I override the serialized name of each list item in a List<SomeStruct>() in c#?

I have a struct more or less like this:

[Serializable]
[XmlRoot("Customer")]
public struct TCustomer
{
string CustomerNo;
string Name;
}


I sometimes serialize this this struct to XML as a single object, which works fine, but I also sometimes need to serialize a List<> of this struct.

I've used this to set the top level element name:

[Serializable]
[XmlRoot("Customers")]
public class CustomerList : List<TCustomer> { }


XmlSerializer however, insists on calling each list item TCustomer. How can I tell XmlSerializer to use the name Customer instead of TCustomer?

Answer Source

Thank's for all the answers. The sollution to my specific problem however, turned out to be as simple as:

[XmlRoot("Customers")]
public class Customers
{
    [XmlElement("Customer")]
    public List<TCustomer> List = new List<TCustomer>();
}