我试图序列化一个虚拟的订单集合,其中每个订单都包含一个产品。该集合正在序列化,但订单内的示例产品属性正在被遗漏。c#序列化嵌套类
指令集
[XmlRoot("Orders")]
public class OrderCollection : ICollection<Order>
{
private static List<Order> _orders;
private List<Order> Orders
{
get
{
if(_orders == null)
{
_orders = new List<Order>();
}
return _orders;
}
}
//All the ICollection functions
}
订购
public class Order
{
[XmlElement("Id")]
public int Id
{
get;
set;
}
[XmlElement("Title")]
public string Title
{
get;
set;
}
[XmlElement("IsReserved")]
public bool IsReserved
{
get;
set;
}
[XmlElement("Count")]
public int Count
{
get
{
return this.Products.Count;
}
set
{
}
}
// not serializing
[XmlElement("Product")]
public Product ProductTest
{
get
{
return new Product();
}
}
// not serializing
[XmlArray("Products")]
public ICollection<Product> Products
{
get
{
return this._products;
}
}
private List<Product> _products;
public Order()
{
var rand = new Random();
var count = rand.Next(1, 5);
this._products = new List<Product>();
for (int i = 0; i < count; i++)
{
this._products.Add(new Product());
}
}
}
产品
[Serializable]
public class Product
{
[XmlElement("Id")]
public int Id
{
get;
set;
}
[XmlElement("Title")]
public string Title
{
get;
set;
}
public Product()
{
var rand = new Random();
this.Id = rand.Next(100, 9999);
this.Title = "Product " + this.Id;
}
}
输出
<?xml version="1.0"?>
<Orders xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Order>
<Id>619883</Id>
<Title>Order 619883</Title>
<IsReserved>false</IsReserved>
<Count>3</Count>
</Order>
<Order>
<Id>961448</Id>
<Title>Order 961448</Title>
<IsReserved>false</IsReserved>
<Count>3</Count>
</Order>
<Order>
<Id>483677</Id>
<Title>Order 483677</Title>
<IsReserved>false</IsReserved>
<Count>2</Count>
</Order>
<Order>
<Id>512026</Id>
<Title>Order 512026</Title>
<IsReserved>false</IsReserved>
<Count>2</Count>
</Order>
<Order>
<Id>916029</Id>
<Title>Order 916029</Title>
<IsReserved>false</IsReserved>
<Count>4</Count>
</Order>
<Order>
<Id>109800</Id>
<Title>Order 109800</Title>
<IsReserved>false</IsReserved>
<Count>4</Count>
</Order>
</Orders>
我完全困惑。深度序列化似乎正在工作,因为否则顺序不会在OrderCollection内序列化,但它只是停止。有什么建议?
我认为'[的XmlElement( “产品”)]公众的ICollection Products'应该是'[XmlArray( “产品”)]公众的ICollection Products' HTTP ://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayattribute.aspx –
asawyer
我已经尝试过了,为了排除它,我添加了单个ProductTest属性,它不是序列化的。 – Craig
尝试抛开你在那里的所有额外代码。将您的类创建为_simple_ plain-old-CLR对象。没有空置的setter,没有只读属性,没有什么花哨,看看会发生什么。 (另外,为什么后台字段是'private static List _orders;'static?)对于您的XML序列化,您最好使用一个代表您的XML模式的简单数据模型。如果您想要添加业务/逻辑/验证,则可以通过转换到/不考虑序列化问题的内部业务类来单独执行。 –