首先標記你EnvironmentCollection類爲可序列化。然後你可以用下面的代碼進行反序列化XML回到對象:
/// <summary>
/// Deserializes xml file to object
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static object DeSerializeFromXML(string filePath, Type type)
{
object data = null;
System.IO.Stream stream = null;
try
{
stream = System.IO.File.Open(filePath, System.IO.FileMode.Open);
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(type);
data = x.Deserialize(new System.Xml.XmlTextReader(stream));
stream.Close();
stream.Dispose();
}
catch (Exception ex)
{
try
{
stream.Close();
stream.Dispose();
}
catch (Exception)
{
}
throw new Exception(ex.Message);
}
return data;
}
您可以使用此功能是這樣的:
EnvironmentCollection col = (EnvironmentCollection)DeSerializeFromXML("myFile.xml", typeof(EnvironmentCollection));
你需要什麼幫助? [你有什麼嘗試?](http://whathaveyoutried.com) – Adam
如何只加載Env1或Env2的配置通過serilization – Anish