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?
Hope it helps
[XmlType("Customer")]
[XmlRoot("Customer")]
public struct TCustomer
{
public string CustomerNo;
public string Name;
}
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.
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