using System; using System.IO; using System.Xml.Serialization; namespace SMSTest.Comm { public class SerializeHelper { //序列化到xml檔案 注意:檔案將儲存到應用程式同級目錄 public static bool Serialize(Type t,object tValue) { //序列化 try { FileStream fs = new FileStream(t.ToString()+".xml", FileMode.Create); XmlSerializer xs = new XmlSerializer(t); xs.Serialize(fs, tValue); fs.Close(); return true; } catch(Exception ex) { return false; } } //從xml檔案反序列化 注意:檔案放在應用程式同級目錄 public static object DeSerialize(Type t) { if (!File.Exists(t.ToString() + ".xml")) return null; try { FileStream fs = new FileStream(t.ToString() + ".xml", FileMode.Open, FileAccess.Read); XmlSerializer xs = new XmlSerializer(t); return xs.Deserialize(fs); } catch (Exception e) { return null; } } } }
注意要序列化的物件可以控制輸出節點名稱、樣式、是否顯示,方法如下:
[XmlRoot("CatsInfo")] public class CatCollection { [XmlArray("Cats"), XmlArrayItem("Cat")] public Cat[] Cats { get; set; } } [XmlRoot("Cat")] public class Cat { // 定義Color屬性的序列化為cat節點的屬性 [XmlAttribute("color")] public string Color { get; set; } // 要求不序列化Speed屬性 [XmlIgnore] public int Speed { get; set; } // 設定Saying屬性序列化為Xml子元素 [XmlElement("saying")] public string Saying { get; set; } }