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

07-03 1212阅读


  	
    
    
  
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 GetUserInfos()
{
	 xmlPath = Path.Combine("带.xml后缀的xml文件路径");
	 doc = new XmlDocument();
	 doc.Load(xmlPath);
	 root = doc.SelectSingleNode("root");
	  List result = new List();//在这个函数中将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数据加载

C#根据类的public属性加载类中对应字段的XML
(图片来源网络,侵删)
VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]