Add inner element to an XmlArray (Xml.Serialization)
I'm having troubles when serializing a .net type and complying to an XML schema that add an additional container element (List in this case) to a sequence of elements:
<Items>
<List>
<Item>
<Field1/>
<Field2/>
</Item>
<Item>
<Field1/>
<Field2/>
</Item>
</List>
</Items>
it seems that the XmlArray attribute gives only the possibility to map a single element (items) :
[XmlArray("items"开发者_JAVA百科, 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;
}
}
I've had a look at this, and the only way I can see to shape the data like that is to model it with that extra level in your model:
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; } }
}
}
精彩评论