I'm trying to serialize a List of multiple elements (Suppliers, Customers, Products, etc), all deriving from the same class (MasterElement)
public class XMLFile
{
[XmlArray("MasterFiles")]
public List<MasterElement> MasterFiles;
...
}
[XmlInclude(typeof(Supplier))]
[XmlInclude(typeof(Customer))]
public abstract class MasterElement
{
public MasterElement()
{
}
}
[XmlType(TypeName = "Supplier")]
public class Supplier: MasterElement
{
public string SupplierID;
public string AccountID;
}
[XmlType(TypeName = "Customer")]
public class Customer: MasterElement
{
public string CustomerID;
public string AccountID;
public string CustomerTaxID;
}
So far, the XML is parsing, but the current output is
<MasterFiles>
<MasterElement xsi:type="Supplier">
<SupplierID>SUP-000001</SupplierID>
<AccountID>Unknown</AccountID>
</MasterElement>
<MasterElement xsi:type="Customer">
<CustomerID>CLI-000001</CustomerID>
<AccountID>Unknown</AccountID>
<CustomerTaxID>Unknown</CustomerTaxID>
</MasterElement>
</MasterFiles>
but what I want to is
<MasterFiles>
<Supplier>
<SupplierID>SUP-000001</SupplierID>
<AccountID>Unknown</AccountID>
</Supplier>
<Customer>
<CustomerID>CLI-000001</CustomerID>
<AccountID>Unknown</AccountID>
<CustomerTaxID>Unknown</CustomerTaxID>
</Customer>
</MasterFiles>
What am I doing wrong here?
You can use XmlArrayItem to get around this:
public class XMLFile
{
[XmlArray("MasterFiles")]
[XmlArrayItem("Supplier", typeof(Supplier))]
[XmlArrayItem("Customer", typeof(Customer))]
public List<MasterElement> MasterFiles;
}
From the linked MSDN:
The XmlArrayItemAttribute supports polymorphism--in other words, it allows the XmlSerializer to add derived objects to an array.
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