using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Threading;
using System.Xml.Serialization;
using System.IO;
namespace xmldoc和xml序列化
{
[Serializable] //标示下面下面的类为可序列化,没有这个标示不可以进行序列化
public class person //类必须为public,否则会没有访问权限
{
string name;
public string Name {
get
{
return name;
}
set {
name = value;
}
}
int age;
public int Age {
get {
return age;
}
set {
age = value;
}
}
string gender;
public string Gender {
get {
return gender;
}
set {
gender = value;
}
}
}
class Program
{
static void Main(string[] args)
{
//创建一个写文件的流
StreamWriter writer = new StreamWriter(@"C:\Users\sww\Desktop\fs.xml", false, Encoding.GetEncoding("GB2312"));
//将对象保存到list泛型集合中
List<person> list = new List<person>{new person{Name = "张三",Age = 19, Gender="男"},new person{Name = "李四",Age = 18, Gender ="女"}};
//创建序列化对象,构造函数中标识序列化什么类型的对象
XmlSerializer xSerialzer = new XmlSerializer(typeof(List<person>));
//FileStream fs = new FileStream(@"C:\Users\sww\Desktop\fs.xml", FileMode.OpenOrCreate, FileAccess.Write);
//将对象序列化进写文件流
xSerialzer.Serialize(writer, list);
fs.Dispose();
//释放资源,可用using括起来
writer.Dispose();
//以下为反序列化
List<person> plist = new List<person>();
//FileStream f = new FileStream(@"C:\Users\sww\Desktop\fs.xml", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(@"C:\Users\sww\Desktop\fs.xml", Encoding.GetEncoding("GB2312"));
XmlSerializer xs = new XmlSerializer(typeof(List<person>));
plist = (List<person>)xs.Deserialize(reader);
// f.Dispose();
reader.Dispose();
}
}
}
上面的例子,我测试,如果使用filestream文件流序列化后,不能使用streamreader进行反序列化话,只有当使用了streamwriter对象序列化后才能使用streamreader进行反序列化,所以进行序列化时,只能用streamwriter和streamreader成对序列化或者filestream进行序列化和反序列化