gpt4 book ai didi

C# - 派生类的 XML 序列化

转载 作者:数据小太阳 更新时间:2023-10-29 01:45:14 25 4
gpt4 key购买 nike

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

我在这里做错了什么?

最佳答案

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

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

来自链接的 MSDN:

The XmlArrayItemAttribute supports polymorphism--in other words, it allows the XmlSerializer to add derived objects to an array.

关于C# - 派生类的 XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18570657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com