C# - 派生类的XML序列化

时间:2013-09-02 10:11:09

标签: c# xml xml-serialization xmlserializer

我正在尝试序列化多个元素的列表(供应商,客户,产品等),所有元素都来自同一个类(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;
}

到目前为止,XML正在解析,但当前的输出是

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

但我想要的是

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

我在这里做错了什么?

1 个答案:

答案 0 :(得分:7)

您可以使用XmlArrayItem解决此问题:

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

来自链接的MSDN:

  

XmlArrayItemAttribute支持多态 - 换句话说,它支持多态   允许XmlSerializer将派生对象添加到数组中。