首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

.NET XML 序列化集合完全指南:從 List<T> 到多態型別處理

     編輯:關於.NET

基礎集合序列化:List<T> 自動處理

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 屬性宣告已知衍生型別

[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>

進階控制:XmlArrayAttribute 自訂容器元素

若需修改 <Items> 節點名稱或加入屬性,可搭配 [XmlArrayAttribute(ElementName="CustomName", Namespace="...")] 使用,靈活掌控 XML 結構。

適用範圍

本文方法對所有實作 IEnumerable 的集合型別(Array、ArrayList、List、Dictionary、HashTable 等)均有效。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved