using System.Xml.Serialization; using System.IO; using System.Xml; using System.Text; namespace TestProject1.XML { public class XmlRepository<TRoot> { string _FilePath; public XmlRepository(string filePath) { this._FilePath = filePath; } XmlSerializer _Serializer; XmlSerializer Serializer { get { if (_Serializer != null) return _Serializer; _Serializer = new XmlSerializer(typeof(TRoot)); return _Serializer; } } TRoot _Root; public TRoot Root { get { if (_Root != null) return _Root; using (var sm = File.Open(_FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { _Root = (TRoot)Serializer.Deserialize(sm); } return _Root; } } public void Save() { using (var sm = File.Open(_FilePath, FileMode.Truncate)) { //这样写就可有<?xml version="1.0" encoding="utf-8"?> XmlTextWriter write = new XmlTextWriter(sm, Encoding.UTF8); //设置格式缩进 write.Formatting = Formatting.Indented; Serializer.Serialize(write, Root); } } } }