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文件
<?xml version = "1.0" encoding = "UTF-8" ?>
<ModelTest>
<Name>张三</Name>
<Password>123456</Password>
<Settings>
<Int1>123</Int1>
<String1>你好</String1>
<Bool1>true</Bool1>
</Settings>
</ModelTest>