XML序列化和反序列化
使用 System.Xml.Serialization 命名空间中的 XmlSerializer 类来进行 XML 格式的序列化和反序列化。
using System.IO;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Student> stuList = new List<Student>()
{
new Student{ ID = 1,Name="张三",Age = 18 },
new Student{ ID = 2,Name="李四",Age = 19 },
new Student{ ID = 3,Name="王五",Age = 17 }
};
Create_Xml(stuList);
List<Student> list = GetXmlToList();
Console.ReadKey();
}
/// <summary>
/// 生成Xml文件(序列化)
/// </summary>
/// <param name="loginInfo"></param>
private static void Create_Xml(List<Student> loginInfo)
{
var tList = new List<Student>();
foreach (var item in loginInfo)
{
tList.Add(new Student
{
ID = item.ID,
Name = item.Name,
Age = item.Age
});
}
//引用:System.Xml.Serialization;
XmlSerializer xmls = new XmlSerializer(tList.GetType());
//直接调用loginInfo传过来的参数也可以
XmlSerializer xmls = new XmlSerializer(loginInfo.GetType());
FileInfo fileInfo = new FileInfo("loginrememhis.txt");//路径 没有会自动创建
if (fileInfo.Exists)
{
fileInfo.Delete();
}
using (Stream s = fileInfo.OpenWrite())
{
//序列化为xml文档
xmls.Serialize(s, tList);
s.Close();
}
}
/// <summary>
/// 读取Xml文件(反序列化)
/// </summary>
/// <returns>反序列化对象</returns>
public static List<Student> GetXmlToList()
{
var list = new List<Student>();
//引用:System.Xml.Serialization;
XmlSerializer xmls = new XmlSerializer(list.GetType());
FileInfo fileInfo = new FileInfo("loginrememhis.txt");
using (Stream fileStream = fileInfo.OpenRead())
{
//反序列化为对象
list = xmls.Deserialize(fileStream) as List<Student>;
return list;
}
}
}
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
}