1.解析代码
添加引用,
using System.Xml.Linq;
using System.Xml;
using System.Xml.Serialization;
public class SerializerUtil<T> where T : class { public readonly string RootPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config"); //路径 public const string FileName = "config.xml";//文件名 public readonly XmlSerializer XmlSerializer = new XmlSerializer(typeof(T)); private static DateTime? _changeTime;
public bool CheckChanged() { if (_changeTime == null) { _changeTime = new FileInfo(Path.Combine(RootPath, FileName)).LastWriteTime; return true; } var lst = new FileInfo(Path.Combine(RootPath, FileName)).LastWriteTime; if (_changeTime != lst) { _changeTime = lst; return true; } return false; } public void Save(T data) { if (!Directory.Exists(RootPath)) Directory.CreateDirectory(RootPath); var filePath = Path.Combine(RootPath, FileName); using (var sw = new StreamWriter(filePath)) { XmlSerializer.Serialize(sw, data, new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty })); } } public T Read(string filename = "") { var file = string.IsNullOrEmpty(filename) ? FileName : filename + ".xml"; var filePath = Path.Combine(RootPath, file); if (!File.Exists(filePath)) return null; using (var sw = new StreamReader(filePath)) { return XmlSerializer.Deserialize(sw) as T; } } public string FilePath { get { return Path.Combine(RootPath, FileName); } } }
2.T
[XmlRoot("Root")] public class GameIcon { [XmlAttribute("Attribute1")] public string Ver { get; set; } [XmlElement("Element1")] public Info Info1 { get; set; } [XmlElement("Element1")] public Info Info2 { get; set; } } public class Info { [XmlAttribute("width")] public string Width { get; set; } [XmlAttribute("height")] public string Height { get; set; } [XmlAttribute("count")] public string Count { get; set; } }
原文:http://www.cnblogs.com/shuajing/p/5196070.html