Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 451
Thomas Kjørnes Avatar asked Feb 02 '11 13:02

Thomas Kjørnes


2 Answers

Hope it helps

[XmlType("Customer")]
[XmlRoot("Customer")]
public struct TCustomer
{
    public string CustomerNo;
    public string Name;
}
like image 196
Anuraj Avatar answered Nov 10 '22 05:11

Anuraj


The XmlRoot attribute only applies for the root element, so it doesn't apply for TCustomer when you are serializing CustomerList.

Without implementing your own serialization, I don't think you can change TCustomer to serialize as Customer within the CustomerList class. But you can do something like this...

[Serializable]
[XmlRoot("customerList")]
public class CustomerList 
{
    [XmlArray("customers")]
    [XmlArrayItem("customer")]
    public List<TCustomer> Customers { get; set; }
}

That should give you xml similar to:

<customerList>
   <customers>
      <customer />
      <customer />
      <customer />
   </customers>
</customerList>

This changes your CustomerList from a generic list, but it allows you to control your naming.

like image 5
Adam Spicer Avatar answered Nov 10 '22 05:11

Adam Spicer