写在前面
一个常用的对象与Xml序列化工具类,使用系统类库System.Xml,序列化时需要注意只能将对象的公共字段和读/写属性转换为 XML。不转换方法、索引器、私有字段或只读属性。另外XmlSerializer 类无法序列化ArrayList数组和List<T>数组。
using System.Xml.Serialization;
代码实现
public class ObjectSerializer<T> where T : class{public void SerializeToXml(string filePath, object target){var dir = Path.GetDirectoryName(Path.GetFullPath(filePath));if (string.IsNullOrWhiteSpace(dir) || !Directory.Exists(dir))throw new Exception("File Path Invalid");using (var writer = new StreamWriter(filePath)){var xmlSerializer = new XmlSerializer(typeof(T));xmlSerializer.Serialize(writer, target);}}public string SerializeToXml(T target){using (var writer = new StringWriter()){var xmlSerializer = new XmlSerializer(typeof(T));xmlSerializer.Serialize(writer, target);return writer.ToString();}}public T DeserializeFromString(string xml){var xmlSerializer = new XmlSerializer(typeof(T));using (StringReader sr = new StringReader(xml)){return xmlSerializer.Deserialize(sr) as T;}}public T DeserializeFromXml(string filePath){if (!File.Exists(filePath))throw new Exception("File Path Invalid");try{using (var reader = new StreamReader(filePath)){var xmlSerializer = new XmlSerializer(typeof(T));return (T)xmlSerializer.Deserialize(reader);}}catch (Exception ex){return null;}}}