修改代码后,我们再运行,出现如下错误“不应是类型 SerializeCollection.BookItem。使用 XmlInclude 或 SoapInclude 属性静态指定非已知的类型”,看来是系统在做序列化的时候,搞不清楚List中的成员到底是什么类型。这个时候就要使用XmlArrayItem来帮忙了。MyRootClass类的Item成员前加入XmlArrayItem标志。
[XmlArrayItem(ElementName= "Item", IsNullable=true, Type = typeof(Item), Namespace = "http://www.aboutdnn.com"), XmlArrayItem(ElementName = "BookItem", IsNullable = true, Type = typeof(BookItem), Namespace = http://www.aboutdnn.com)]
修改后的代码如下:
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();
/* Uses a more advanced method of creating an list:
create instances of the Item and BookItem, where BookItem
is derived from Item. */
Item item1 = new Item();
// Sets the objects' properties.
item1.ItemName = "Widget1";
item1.ItemCode = "w1";
item1.ItemPrice = 231;
item1.ItemQuantity = 3;
BookItem bookItem = new BookItem();
// Sets the objects' properties.
bookItem.ItemCode = "w2";
bookItem.ItemPrice = 123;
bookItem.ItemQuantity = 7;
bookItem.ISBN = "34982333";
bookItem.Title = "Book of Widgets";
bookItem.Author = "John Smith";
// Sets the class's Items property to the list.
myRootClass.Items.Add(item1);
myRootClass.Items.Add(bookItem);
/* 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<Item>();
}
private List<Item> items;
[XmlArrayItem(ElementName = "Item",
IsNullable = true,
Type = typeof(Item),
Namespace = "http://www.aboutdnn.com"),
XmlArrayItem(ElementName = "BookItem",
IsNullable = true,
Type = typeof(BookItem),
Namespace = "http://www.aboutdnn.com")]
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;
}
public class BookItem : Item
{
public string Title;
public string Author;
public string ISBN;
}
}
发表评论