[Serializable]
public class Person
{
public string Name{get;set;}
public bool Sex{get;set;}}
class Porgram
{
public staticvoid SerializeToXml<T>(object obj,string path){
FileStream xmlFile = new FileStream(path,FileMode.OpenOrCreate);
XmlSerializer xml = new XmlSerializer(typeof(T));
try
{
xml.Serialize(xmlFile,obj);
xmlFile.Close();}catch
{
throw;}}staticvoidMain(string[] args){
Person a = new Person();
a.name ="Gets";
a.age = false;
SerializeToXml<Person>(a,$"D:/123.xml");}}
将XML文件转反序列化成Object对象
class Porgram
{
public static T DeserializeToObject<T>(string path){
try
{
FileStream xmlFile = new FileStream(path, FileMode.Open);
XmlSerializer xml = new XmlSerializer(typeof(T));
T t =(T)xml.Deserialize(xmlFile);
xmlFile.Close();return t;}catch
{
throw;}}staticvoidMain(string[] args){
var a = DeserializeToObject<Person>($"D:/123.xml");}}
XML文件的序列化和反序列化
public class Student: SerializableConfig
{[XmlAttribute(Namespace ="http://www.cpandl.com")]
public string GroupName;[XmlAttribute(DataType ="base64Binary")]
public Byte[] GroupNumber;[XmlAttribute(DataType ="date", AttributeName ="CreationDate")]
public DateTime Today;[XmlAttribute]
public string Name { get; set;}
public List<College> Coll { get; set;}
public Student(){
Coll = new List<College>();}}
public class College
{[XmlAttribute]
public string ID { get; set;}[XmlAttribute]
public string Age { get; set;}}//---------------------------------------------------------------------staticvoidMain(string[] args){
Student st = new Student();
st.GroupName =".Net";
Byte[] hexByte = new Byte[2]{ Convert.ToByte(100), Convert.ToByte(50)};
st.GroupNumber = hexByte;
DateTime date = new DateTime(2001,1,1);
st.Today = date;
st.Name ="Kkarot";
st.Coll.Add(new College(){ Age ="11", ID ="10245412"});
st.Coll.Add(new College(){ Age ="KK", ID ="CC"});
st.SerializeObject("kakarot.xml");
Student s = new Student();
s.Load("kakarot.xml");
Console.ReadKey();}
SerializableConfig类
public class SerializableConfig
{
public voidLoad(string filename){
Stream fstream = new FileStream(filename, FileMode.Open);
XmlSerializer xml = new XmlSerializer(GetType());
var obj = xml.Deserialize(fstream);
PropertyInfo[] pros = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);// 表示当前 System.Type 的匹配指定绑定约束的所有属性的 System.Reflection.PropertyInfo 对象数组
foreach (var p in pros){if(p.CanWrite && p.GetCustomAttribute<XmlIgnoreAttribute>()== null){
var obj_item = p.GetValue(obj);//返回指定对象的属性值
p.SetValue(this, obj_item);//设置指定对象的属性值}}
fstream.Close();}
public voidSerializeObject(string filename){
XmlSerializer my = new XmlSerializer(GetType());
TextWriter writer = new StreamWriter(filename);
my.Serialize(writer, this);
writer.Close();}}