C#基础拾遗02-XML串行化
1. 什么叫串行化?
串行化(Serialize)是指将对象存储到介质(如文件、内存缓冲区等)中或是以二进制方式通过网络传输。反串行化(Deserialize)指将这些连续的数据重新构建一个与原始对象状态相同的对象
2. 串行化分类两种形式
- 二进制串行化
串行化时数据以二进制形式存入文件。但是该方式不适合同其他非.NET程序交换数据。
- XML串行化
对象的公共属性以XML元素和特性表示。该方式可以和其他非.NET程序交换数据。该方法要引用命名空间using System.Xml.Serialization;
另外,XML串行化器是不能针对枚举类型串行化操作的,如果有必要的话,可以将枚举型变量设置为私有变量,并且设置相应的简单类型变量进行操作。
3. 实例
首先创建我们要串行化的类:
public class Book
{
public string _title;
public int _page;
public string[] _Part;
public string _author;
public float _price;
}
{
public string _title;
public int _page;
public string[] _Part;
public string _author;
public float _price;
}
- 串行化对象
void SerializeObject(Book[] book)
{
try
{
XmlSerializer ser = new XmlSerializer(typeof(Book[]), new XmlRootAttribute("Books"));//声明对象,并且添加根节点
StreamWriter sw = new StreamWriter("book.prt");
ser.Serialize(sw, book);
sw.Close();
}
catch (Exception e)
{
MessageBox.Show("串行化失败:" + e.Message.ToString());
}
}
调用:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
private void Serialize_Click(object sender, EventArgs e)
{
Book book = new Book();
book._title = "西游记";
book ._author="吴承恩";
book._page = 420;
book._Part = new string[]{"第一章?", "第二章?", "第三章?", "..."};
book._price = 55;
。。。。。
Book[] books = new Book[2] { book, book2 };
SerializeObject(books );
}
{
Book book = new Book();
book._title = "西游记";
book ._author="吴承恩";
book._page = 420;
book._Part = new string[]{"第一章?", "第二章?", "第三章?", "..."};
book._price = 55;
。。。。。
Book[] books = new Book[2] { book, book2 };
SerializeObject(books );
}
此时打开book.prt文件,如下图所示。
- 反串行化方法
private Book[] DeserializeObject()
{
FileStream fs = new FileStream("book.prt", FileMode.Open);
XmlSerializer ser = new XmlSerializer(typeof(Book[]), new XmlRootAttribute("Books"));
Book[] books = (Book[])ser.Deserialize(fs);
return books;
}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Book[] books = DeserializeObject();
foreach (Book b in books)
{
string s = b._title + ":" + b._author + "," + b._price + ",";
listBox1.Items.Add(s);
}
foreach (Book b in books)
{
string s = b._title + ":" + b._author + "," + b._price + ",";
listBox1.Items.Add(s);
}
结果如下:
作者:陈敬(公众号:敬YES)
出处:http://www.cnblogs.com/janes/
博客文章仅供交流学习,请勿用于商业用途。如需转载,请务必注明出处。