class Common
{
/// <summary> /// 將XML文件寫入指定的對象 /// </summary> /// <param name="xmlFile">xml絕對路徑</param> /// <param name="type">序列的類型,要與XML對應的類</param> /// <returns>將對象返回,當文件操作失敗則返回Null值</returns> public static object DeserializeXmlToObject(
string xmlFile, Type type)
{
XmlSerializer mySerializer =
new XmlSerializer(type);
using (FileStream stream =
new FileStream(xmlFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
return mySerializer.Deserialize(stream);
}
}
/// <summary> /// 將對象寫入到XML中 /// </summary> /// <param name="obj">數據源對象</param> /// <param name="xmlFile">目標路徑</param> /// <param name="type">轉換類型</param> public static void SerializeObjectToXml(
object obj, String xmlFile, Type type)
{
XmlSerializer mySerializer =
new XmlSerializer(type);
using (FileStream stream =
new FileStream(xmlFile, FileMode.Create, FileAccess.Write, FileShare.Read))
{
mySerializer.Serialize(stream, obj);
}
}
}