XmlSerializer 內建支援所有實作 IEnumerable 的集合。基本用法:
[Serializable]
public class MyRootClass {
public MyRootClass() { items = new List<Item>(); }
private List<Item> items;
public List<Item> Items { get { return items; } set { items = value; } }
}
public class Item {
[XmlElement(ElementName = "OrderItem")]
public string ItemName;
public string ItemCode;
public decimal ItemPrice;
public int ItemQuantity;
}
// 序列化
XmlSerializer s = new XmlSerializer(typeof(MyRootClass));
s.Serialize(myWriter, myRootClass);
輸出 XML:
<MyRootClass>
<Items>
<Item>
<OrderItem>Widget1</OrderItem>
<ItemCode>w1</ItemCode> ...
</Item>
</Items>
</MyRootClass>
當 List<Item> 實際包含 BookItem : Item 子類別實例時,直接序列化會拋出:
「不應為類型 BookItem。使用 XmlInclude 或 SoapInclude 靜態指定非已知類型。」
[XmlArrayItem(ElementName = "Item", IsNullable = true, Type = typeof(Item), Namespace = "https://www.aboutdnn.com"),
XmlArrayItem(ElementName = "BookItem", IsNullable = true, Type = typeof(BookItem), Namespace = "https://www.aboutdnn.com")]
public List<Item> Items { get; set; }
<Items>
<Item xmlns="https://www.aboutdnn.com">
<OrderItem>Widget1</OrderItem> ...
</Item>
<BookItem xmlns="https://www.aboutdnn.com">
<ItemCode>w2</ItemCode> ...
<Title>Book of Widgets</Title>
<Author>John Smith</Author>
<ISBN>34982333</ISBN>
</BookItem>
</Items>
若需修改 <Items> 節點名稱或加入屬性,可搭配 [XmlArrayAttribute(ElementName="CustomName", Namespace="...")] 使用,靈活掌控 XML 結構。
本文方法對所有實作 IEnumerable 的集合型別(Array、ArrayList、List、Dictionary、HashTable 等)均有效。