2013-09-02 14 views
8

Próbuję serializacji listę wielu elementów (dostawców, klientów, produktów, itp), wszyscy wywodzący się z tej samej klasy (MasterElement)C# - XML ​​serializacji klas pochodnych

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; 
} 

tej pory XML jest analizowanie, ale prąd wyjściowy jest

<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> 

ale to, co chcę jest

<MasterFiles> 
    <Supplier> 
     <SupplierID>SUP-000001</SupplierID> 
     <AccountID>Unknown</AccountID> 
    </Supplier> 
    <Customer> 
     <CustomerID>CLI-000001</CustomerID> 
     <AccountID>Unknown</AccountID> 
     <CustomerTaxID>Unknown</CustomerTaxID> 
    </Customer> 
</MasterFiles> 

Co am Robię źle tutaj?

Odpowiedz

7

Można użyć XmlArrayItem aby obejść ten problem:

public class XMLFile 
{ 
    [XmlArray("MasterFiles")] 
    [XmlArrayItem("Supplier", typeof(Supplier))] 
    [XmlArrayItem("Customer", typeof(Customer))] 
    public List<MasterElement> MasterFiles; 
} 

Od połączonego MSDN:

XmlArrayItemAttribute wspiera polimorfizmu - innymi słowy, pozwala XmlSerializer aby dodawać obiekty pochodzące do tablicy.

+0

Dzięki, działało idealnie :) –

Powiązane problemy