Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - XML serialization of derived classes

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?

like image 807
Joao Batista Avatar asked Sep 02 '13 10:09

Joao Batista


1 Answers

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.

like image 142
DavidN Avatar answered Oct 07 '22 15:10

DavidN