8

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

我在这里做错了什么?

4

1 回答 1

7

您可以使用XmlArrayItem来解决这个问题:

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

从链接的 MSDN:

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

于 2013-09-02T10:24:34.423 回答