C#根据类的public属性加载类中对应字段的XML

发布于:2024-07-03 ⋅ 阅读:(99) ⋅ 点赞:(0)
<?xml version="1.0" encoding="utf-8"?>
<root>
  	<UserLogin ID="0" UserName="" UserPassWord="" Level="1" PowerName="默认用户" PowerID="0" Remark="" IsEnabled="True"/>
    <UserLogin ID="1" UserName="" UserPassWord="123" Level="2" PowerName="管理员" PowerID="0" Remark="" IsEnabled="True"/>
    <UserLogin ID="2" UserName="Administrator" UserPassWord="123" Level="3" PowerName="超级管理员" PowerID="0" Remark="" IsEnabled="True"/>
  </root>
public partial class UserLogin
{
   
    private int id;
  
    public int ID
    {
        get=>id; set=>id = value;
    }
    private string userName;
  
    public string UserName
    {
        get => userName;
        set => userName=value;
    }
    private string userPassWord;

   
    public string UserPassWord
    {
        get => userPassWord;
        set =>userPassWord=value ;
    }
    private int _level;

   
    public int Level
    {
        get => _level;
        set => _level=value;
    }
    private string powerName;
    public string PowerName
    {
        get => powerName;
        set => powerName=value;
    }
    private int powerID;
    public int PowerID
    {
        get => powerID;
        set => powerID=value;
    }
   
    private string remark;

    
    public string Remark
    {
        get => remark;
        set => remark=value;
    }
    private bool isEnabled;

    
    public bool IsEnabled
    {
        get => isEnabled;
        set => isEnabled=value;
    }
}
public List<UserLogin> GetUserInfos()
{
	 xmlPath = Path.Combine("带.xml后缀的xml文件路径");
	 doc = new XmlDocument();
	 doc.Load(xmlPath);
	 root = doc.SelectSingleNode("root");
	  List<UserLogin> result = new List<UserLogin>();//在这个函数中将UserLogin改成T可以用作泛型类的xml统一加载
	 foreach (XmlElement xl in root.ChildNodes)
	 {
	     UserLogin item = new UserLogin();
	     var properties = typeof(UserLogin).GetProperties();
	     foreach (PropertyInfo pi in properties)
	     {
	         var attribute = xl.GetAttribute(pi.Name);
	         if (attribute != null)
	         {
	             var value = Convert.ChangeType(attribute, pi.PropertyType);
	             //给item的属性赋值
	             pi.SetValue(item, value);
	         }
	     }
	     result.Add(item);
	
	 }
	 return result;
}

可用于泛型类的xml数据加载


网站公告

今日签到

点亮在社区的每一天
去签到