最近在整理一些C#内容,自己写一点东西算是做个笔记。
通过序列化将 类 的属性 直接存入XML文件中;
先定义一个User类
public class User
{
private string _userName;
private string _password;
private string _level;
public User()
{
}
/// <summary>
/// 用户包含 姓名,密码,以及等级
/// </summary>
/// <param name="userName">用户名</param>
/// <param name="password">密码</param>
/// <param name="level">用户等级</param>
public User(string userName, string password,string level)
{
_userName = userName;
_password = password;
_level = level;
}
/// <summary>
/// 用户名
/// </summary>
public string UserName { get => _userName; set => _userName = value; }
/// <summary>
/// 密码
/// </summary>
public string Password { get => _password; set => _password = value; }
/// <summary>
/// 用户等级
/// </summary>
public string Level { get => _level; set => _level = value; }
}
建立保存方法
/// <summary>
/// 保存List到XML文件中
/// </summary>
/// <param name="list"></param>
/// <param name="name"></param>
public static void XmlSaveList(List<T> list, string name)
{
using (StringWriter stringWriter = new StringWriter(new StringBuilder()))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<T>),new XmlRootAttribute(name));
xmlSerializer.Serialize(stringWriter, list);
FileStream fs = new FileStream($"{name}.xml", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs, new UnicodeEncoding(false, false));
sw.Write(stringWriter.ToString());
sw.Close();
fs.Close();
}
}
使用
userList.Add(new User("操作工", "111111", "A"));
userList.Add(new User("工程师", "123456", "B"));
Serialize<User>.XmlSaveList(userList, "Users");
读取XML文件到 List<T>中(List(user))
/// <summary>
/// 读取XMl 到 List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path">XML文件</param>
/// <param name="rootName">根节点</param>
/// <returns></returns>
public static List<T> XmlToList<T>(string path, string rootName) where T : class
{
XmlSerializer serializer = new XmlSerializer(typeof(List<T>), new XmlRootAttribute(rootName));
List<T> list;
using (Stream reader = new FileStream(path, FileMode.Open))
{
list = serializer.Deserialize(reader) as List<T>;
}
return list;
}
使用
//读取文件中的用户信息
userList = Serialize<User>.XmlToList<User>(path, "Users");