C# XmlSerializer序列化浅析
C# 中使用 XmlSerializer 实现类和xml文件的序列化和反序列化,使用起来非常简单。
C# XmlSerializer实现序列化:
XmlSerializer xml = new XmlSerializer(typeof(ClassName));
FileStream fs = new FileStream(@"d:\t.xml",FileMode.Create);
xml.Serialize(fs, new Class());
fs.Close();
C# XmlSerializer实现反序列化:
FileStream fs = new FileStream(@"d:\t.xml", FileMode.Open);
XmlSerializer xml = new XmlSerializer(typeof(ClassName));
ClassName t = (ClassName)xml.Deserialize(fs);
C# XmlSerializer类与主流的序列化类的几个不同点是:
1、不需要Serializable属性,使用XmlIgnore属性标记不需要序列化的属性。
2、该类不能安全地访问私有变成员,所以学要将私有成员改为公共成员,或者提供合适的公共特性。
3、要求被序列化的类要有一个默认的构造器。
下面上个实例,直接上代码:
1、需要序列化的类
[XmlRoot("Person")]
public class Person
{
[XmlElement("name")]
public string Name { get; set; }
[XmlAttribute("sex")]
public byte Sex { get; set; }
[XmlAttribute("age")]
public int Age { get; set; }
[XmlText]
public string Description { get; set; }
[XmlElement("child")]
public
List<Person> Childrens { get; set; }
[XmlElement("childlist")]
public
ChildList ChildList { get; set; }
}
请注意红色标注的属性,生成的xml文件是不一样的^_^
[XmlRoot("Childs")]
public class ChildList
{
[XmlElement("person")]
public List<Person> Childs { get; set;
}
}
2、声明对象
Person person = new Person { Name="张三", Sex=1, Age=25,
Description="我是一名中国人!!" };
person.Childrens = new List<Person>();
person.Childrens.Add(new Person { Name="Boy", Sex=1, Age=5,
Description="我是男孩" });
person.Childrens.Add(new Person { Name="Girl", Sex=0,
Age=10, Description="我是女孩" });
person.ChildList = new ChildList();
person.ChildList.Childs =
new List<Person>();
person.ChildList.Childs.Add(new Person
{ Name = "Jon", Sex = 1, Age = 5 });
person.ChildList.Childs.Add(new Person { Name = "KG", Sex = 0, Age = 10 });
3、序列化
string path = System.AppDomain.CurrentDomain.BaseDirectory;
using (FileStream fs = new FileStream(path + "parson.xml", FileMode.Create))
{
serializer.Serialize(fs, person);
fs.Close();
}
4、反序列化
using (FileStream fs = new FileStream(path + "parson.xml",
FileMode.Open))
{
person =
(Person)serializer.Deserialize(fs);
fs.Close();
}