C# - 派生类的XML序列化 [英] C# - XML serialization of derived classes
本文介绍了C# - 派生类的XML序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图序列化多个元素(供应商,客户,产品等)的名单,都来自同一个类(MasterElement)
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;
}
到目前为止,XML被解析,但当前输出是对>
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?
推荐答案
您可以使用 XmlArrayItem 来解决这个问题:
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;
}
从链接的MSDN:
From the linked MSDN:
的XmlArrayItemAttribute支持多态性 - 换句话说,它
允许XmlSerializer的派生对象添加到阵列
The XmlArrayItemAttribute supports polymorphism--in other words, it allows the XmlSerializer to add derived objects to an array.
这篇关于C# - 派生类的XML序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文