ASP.NET XML序列化
整理一下ASP.NET里面如何序列化实体为XML,获取解析XML内容为实体。
第一步要添加程序集引用,项目-->引用-->鼠标右键-->添加引用-->选择程序集-->System.Xml
工具类代码
/// <summary> /// XML序列化公共处理类 /// </summary> public static class XmlSerializeHelper { /// <summary> /// 将实体对象转换成XML /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="obj">实体对象</param> public static string XmlSerialize<T>(T obj) { try { using (StringWriter sw = new StringWriter()) { Type t = obj.GetType(); XmlSerializer serializer = new XmlSerializer(obj.GetType()); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", "");//把命名空间设置为空 serializer.Serialize(sw, obj,ns); sw.Close(); return sw.ToString(); } } catch (Exception ex) { throw new Exception("将实体对象转换成XML异常", ex); } } /// <summary> /// 将XML转换成实体对象 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="strXML">XML</param> public static T DESerializer<T>(string strXML) where T : class { try { using (StringReader sr = new StringReader(strXML)) { strXML = Regex.Replace(strXML, @"<\?xml*.*?>", "", RegexOptions.IgnoreCase); XmlSerializer serializer = new XmlSerializer(typeof(T)); return serializer.Deserialize(sr) as T; } } catch (Exception ex) { throw new Exception("将XML转换成实体对象异常", ex); } } }
文件流转成XML
var xmlDoc = new XmlDocument(); try { var stream = new Stream(); xmlDoc.Load(stream); //加载XML文档 var entryInfo = XmlSerializeHelper.DESerializer<Model>(xmlDoc.OuterXml); if (entryInfo != null) { // 逻辑处理 } else { //逻辑处理 } } catch (Exception ex) { //异常处理 }