在C#中,可以用XmlSerializer类来反序列化与序列化xml,但我们也可以封装一下,可以使用起来更方便
将XML字符串反序列化成对象 方法
/// <summary> /// 将XML字符串反序列化成对象 /// </summary> /// <typeparam name="T">返回的对象类型</typeparam> /// <typeparam name="xml">xml字符串</typeparam> /// <typeparam name="xmlRootName">xml根节点</typeparam> /// <returns>返回对象类型</returns> public static T Deserialize<T>(string xml, string xmlRootName = "Root") { T result = default(T); using (StringReader sr = new StringReader(xml)) { XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ? new XmlSerializer(typeof(T)) : new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName)); result = (T)xmlSerializer.Deserialize(sr); } return result; }
将XML文件反序列化成对象 方法
/// <summary> /// 将XML文件反序列化成对象 /// </summary> /// <typeparam name="T">返回的对象类型</typeparam> /// <typeparam name="xml">文件路径</typeparam> /// <typeparam name="xmlRootName">xml根节点</typeparam> /// <returns>返回对象类型</returns> public static T DeserializeFile<T>(string filePath, string xmlRootName = "Root") { T result = default(T); if (File.Exists(filePath)) { using (StreamReader reader = new StreamReader(filePath)) { XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ? new XmlSerializer(typeof(T)) : new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName)); result = (T)xmlSerializer.Deserialize(reader); } } return result; }
将对象序列化成XML字符串 方法
/// <summary> /// 将对象序列化成XML字符串 /// </summary> /// <typeparam name="sourceObj">数据对象</typeparam> /// <typeparam name="xmlRootName">xml根节点</typeparam> /// <returns>xml字符串</returns> public static string Serializer(object sourceObj, string xmlRootName = "Root") { MemoryStream Stream = new MemoryStream(); Type type = sourceObj.GetType(); XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ? new XmlSerializer(type) : new XmlSerializer(type, new XmlRootAttribute(xmlRootName)); xmlSerializer.Serialize(Stream, sourceObj); Stream.Position = 0; StreamReader sr = new StreamReader(Stream); string str = sr.ReadToEnd(); sr.Dispose(); Stream.Dispose(); return str; }
将对象序列化成XML文件 方法
/// <summary> /// 将对象序列化成XML文件 /// </summary> /// <typeparam name="filePath">xml文件路径</typeparam> /// <typeparam name="sourceObj">数据对象</typeparam> /// <typeparam name="xmlRootName">xml根节点</typeparam> public static void SerializerFile(string filePath, object sourceObj, string xmlRootName = "Root") { if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null) { Type type = sourceObj.GetType(); using (StreamWriter writer = new StreamWriter(filePath)) { XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ? new XmlSerializer(type) : new XmlSerializer(type, new XmlRootAttribute(xmlRootName)); xmlSerializer.Serialize(writer, sourceObj); } } }