Collection 主要是指像 Array, ArrayList, List, Dictionary, HashTable 这些数据类型,大家平时用
的很多。如果一个类中有一个 Collection 类型的成员,在对这个类进行 XML 序列化的时候,
应该如何处理?应该说在.net 当中这是比较简单的,只要建立一个 XmlSerializer 类就可以帮
你自动搞定,不过有的时候你可能需要对自动的序列化过程施加更多的控制,比如 XML 的
结构是实现固定的,你必须按照要求去生成 XML 结构。
使用不同的属性可以灵活的控制生成的 XML,这里我就不多介绍了,主要讲一下如何序列
化比较复杂的 Collection 结构。下面的方法,对于所有实现了 IEnumerable 接口的 Collection
都有效。
我使用 MSDN 中的例子,不过没有使用数组或者 ArrayList,而是使用了比较高级的数据类
型 List,希望在讲解如何序列化 XML 的同时给使用 List的同学提供点参考。
序列化一个 List
下面的代码示范了如何序列化一个 List,实际上和序列化其它类一样,把这个类扔给
Serialize()函数即可。
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace SerializeCollection
{
class Program
{
static void Main(string[] args)
{
Program test = new Program();
test.SerializeDocument("e:\\books.xml");
}
public void SerializeDocument(string filename)
{
// Creates a new XmlSerializer.
XmlSerializer s =
new XmlSerializer(typeof(MyRootClass));
// Writing the file requires a StreamWriter.
TextWriter myWriter = new StreamWriter(filename);
// Creates an instance of the class to serialize.
MyRootClass myRootClass = new MyRootClass();
//create items
Item item1 = new Item();
// Sets the objects' properties.
item1.ItemName = "Widget1";
item1.ItemCode = "w1";
item1.ItemPrice = 231;
item1.ItemQuantity = 3;
Item item2 = new Item();
// Sets the objects' properties.
item2.ItemName = "Widget2";
item2.ItemCode = "w2";
item2.ItemPrice = 800;
item2.ItemQuantity = 2;
// Sets the class's Items property to the list.
myRootClass.Items.Add(item1);
myRootClass.Items.Add(item2);
/* Serializes the class, writes it to disk, and closes
the TextWriter. */
s.Serialize(myWriter, myRootClass);
myWriter.Close();
}
}
// This is the class that will be serialized.
[Serializable]
public class MyRootClass
{
}
public MyRootClass()
{
}
items = new List- ();
private List
- items;
public List
- 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;
}
}
最后序列化成的 XML:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-
Widget1
w1
231
3
-
Widget2
w2
800
2