序列化.net类型并遵守XML模式时遇到麻烦,该模式将一个额外的容器元素(在本例中为List)添加到元素序列中:
<Items>
<List>
<Item>
<Field1/>
<Field2/>
</Item>
<Item>
<Field1/>
<Field2/>
</Item>
</List>
</Items>
似乎XmlArray属性只提供映射单个元素(项)的可能性:
[XmlArray("items", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[XmlArrayItem("item", typeof(OrderItemsItem), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
public OrderItemsItem[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
答案 0 :(得分:0)
我已经看过这个,我可以看到塑造数据的唯一方法就是在模型中使用额外的级别对其进行建模:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml.Serialization;
static class Program
{
static void Main()
{
var foo = new Foo { Items = { new OrderItemsItem(), new OrderItemsItem() } };
var ser = new XmlSerializer(typeof(Foo));
ser.Serialize(Console.Out, foo);
}
}
public class OrderItemsItem { }
public class Foo
{
private FooItems items = new FooItems();
// this one is for serialization, but tried to be invisible otherwise
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
[XmlElement("Items")]
public FooItems WrappedItems { get { return items; } set { items = value; } }
// this one is for general use
[XmlIgnore]
public List<OrderItemsItem> Items { get { return items.Items; } }
public class FooItems
{
private readonly List<OrderItemsItem> items = new List<OrderItemsItem>();
[XmlArray("List"), XmlArrayItem("Item")]
public List<OrderItemsItem> Items { get { return items; } }
}
}