C#从Xml文件中读取数据转化成对象

namespace Xml_Model
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ModelTest modelTest = Method1(System.Environment.CurrentDirectory+@"\test.xml", typeof(ModelTest)) as ModelTest;
        }

        public static object Method1(string path, Type type)
        {
            object result;
            try
            {
                XmlSerializer xml = new XmlSerializer(type);
                using (StreamReader sr = new StreamReader(path))
                {
                    result = xml.Deserialize(sr);
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            return result;
        }


    }




    public class ModelTest
    {
        public string Name { get; set; }
        public string Password { get; set; }

        public Settings Settings { get; set; } = new Settings();
    }

    public class Settings
    {
        public int Int1 {  get; set; }
        public string String1 {  get; set; }
        public Boolean Bool1 { get; set; }
    }
}

xml文件 



	张三
	123456
	
		123
		你好
		true
	

你可能感兴趣的:(c#,xml)