XmlSerializer 构造函数 (Type, String) 将指定类型的对象序列化为 XML 文档,也可以将 XML 文档反序列化为指定类型的对象

 private void SerializeObject(string filename) {
XmlSerializer serializer = new XmlSerializer
(typeof(OrderedItem), "http://www.cpandl.com");

// Create an instance of the class to be serialized.
OrderedItem i = new OrderedItem();

// Insert code to set property values.

// Writing the document requires a TextWriter.
TextWriter writer = new StreamWriter(filename);
// Serialize the object, and close the TextWriter
serializer.Serialize(writer, i);
writer.Close();
}

private void DeserializeObject(string filename) {
XmlSerializer serializer = new XmlSerializer
(typeof(OrderedItem), "http://www.cpandl.com");
// A FileStream is needed to read the XML document.
FileStream fs = new FileStream(filename, FileMode.Open);

// Declare an object variable of the type to be deserialized.
OrderedItem i;

// Deserialize the object.
i = (OrderedItem) serializer.Deserialize(fs);

// Insert code to use the properties and methods of the object.
}
posted @ 2012-03-23 15:28  大笑江湖  阅读(423)  评论(0编辑  收藏  举报