以下是一个包装的用于序列化反序列化XML和C# 对象的类。
 public class XmlSerializeHelper<T>
    {
        #region Serialize/Deserialize
        private static System.Xml.Serialization.XmlSerializer serializer;
        private static System.Xml.Serialization.XmlSerializer Serializer
        {
            get
            {
                if ((serializer == null))
                {
                    serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                }
                return serializer;
            }
        }
        /// <summary>
        /// Serializes object into an XML document
        /// </summary>
        /// <returns>string XML value</returns>
        public virtual string Serialize()
        {
            System.IO.StreamReader streamReader = null;
            System.IO.MemoryStream memoryStream = null;
            try
            {
                memoryStream = new System.IO.MemoryStream();
                Serializer.Serialize(memoryStream, this);
                memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                streamReader = new System.IO.StreamReader(memoryStream);
                return streamReader.ReadToEnd();
            }
            catch
            {
               
            }
            finally
            {
                if ((streamReader != null))
                {
                    streamReader.Dispose();
                }
                if ((memoryStream != null))
                {
                    memoryStream.Dispose();
                }
            }
            return "";
        }
        /// <summary>
        /// Deserialize xml string into an  object
        /// </summary>
        /// <param name="xml">string to deserialize</param>
        /// <param name="obj">Output object</param>
        /// <param name="exception">output Exception value if deserialize failed</param>
        /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
        public static bool Deserialize(string xml, out T obj, out System.Exception exception)
        {
            exception = null;
            obj = default(T);
            try
            {
                obj = Deserialize(xml);
                return true;
            }
            catch (System.Exception ex)
            {
                exception = ex;
                return false;
            }
        }
        /// <summary>
        /// Deserialize xml string into an  object
        /// </summary>
        /// <param name="xml">string to deserialize</param>
        /// <param name="obj">Output object</param>
        /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
        public static bool Deserialize(string xml, out T obj)
        {
            System.Exception exception = null;
            return Deserialize(xml, out obj, out exception);
        }
        /// <summary>
        /// Deserialize xml file into  construct.
        /// </summary>
        /// <param name="xml">string to deserialize</param>
        /// <returns>object if this XmlSerializer can deserialize the object</returns>
        public static T Deserialize(string xml)
        {
            System.IO.StringReader stringReader = null;
            try
            {
                stringReader = new System.IO.StringReader(xml);
                return ((T)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
            }
            catch
            {
                //
            }
            finally
            {
                if ((stringReader != null))
                {
                    stringReader.Dispose();
                }
            }
            return default(T);
        }
        /// <summary>
        /// Serializes current object into file
        /// </summary>
        /// <param name="fileName">full path of output xml file</param>
        /// <param name="exception">output Exception value if failed</param>
        /// <returns>true if can serialize and save into file; otherwise, false</returns>
        public virtual bool SaveToFile(string fileName, out System.Exception exception)
        {
            exception = null;
            try
            {
                SaveToFile(fileName);
                return true;
            }
            catch (System.Exception e)
            {
                exception = e;
                return false;
            }
        }
        /// <summary>
        /// Serializes current object into file
        /// </summary>
        /// <param name="fileName">full path of output xml file</param>
        /// <returns>true if can serialize and save into file; otherwise, false</returns>
        public virtual void SaveToFile(string fileName)
        {
            System.IO.StreamWriter streamWriter = null;
            try
            {
                string xmlString = Serialize();
                System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
                streamWriter = xmlFile.CreateText();
                streamWriter.WriteLine(xmlString);
                streamWriter.Close();
            }
            catch
            {
                //
            }
            finally
            {
                if ((streamWriter != null))
                {
                    streamWriter.Dispose();
                }
            }
        }
        /// <summary>
        /// Deserialize xml markup from file into an  object
        /// </summary>
        /// <param name="fileName">string xml file to load and deserialize</param>
        /// <param name="obj">Output  object</param>
        /// <param name="exception">output Exception value if deserialize failed</param>
        /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
        public static bool LoadFromFile(string fileName, out T obj, out System.Exception exception)
        {
            exception = null;
            obj = default(T);
            try
            {
                obj = LoadFromFile(fileName);
                return true;
            }
            catch (System.Exception ex)
            {
                exception = ex;
                return false;
            }
        }
        /// <summary>
        /// Deserialize xml markup from file into an  object
        /// </summary>
        /// <param name="fileName">string xml file to load and deserialize</param>
        /// <param name="obj">Output  object</param>
        /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
        public static bool LoadFromFile(string fileName, out T obj)
        {
            System.Exception exception = null;
            return LoadFromFile(fileName, out obj, out exception);
        }
        /// <summary>
        /// Deserialize xml markup from file into an  object
        /// </summary>
        /// <param name="fileName">string xml file to load and deserialize</param>
        /// <returns></returns>
        public static T LoadFromFile(string fileName)
        {
            System.IO.FileStream file = null;
            System.IO.StreamReader sr = null;
            try
            {
                file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
                sr = new System.IO.StreamReader(file);
                string xmlString = sr.ReadToEnd();
                sr.Close();
                file.Close();
                return Deserialize(xmlString);
            }
            catch
            {
            }
            finally
            {
                if ((file != null))
                {
                    file.Dispose();
                }
                if ((sr != null))
                {
                    sr.Dispose();
                }
            }
            return default(T);
        }
        #endregion
    }

C# 序列化反序列化XML的帮助类的更多相关文章

  1. 学习C# XmlSerializer 序列化反序列化XML

    类.变量常用头: [XmlRootAttribute]:对根节点的描述,在类声明中使用 如:下例的Html类 [XmlType]:对节点描述,在类声明中使用         如:下例的Head类 [X ...

  2. 05-06 Flutter JSON和序列化反序列化、创建模型类转换Json数据、轮播图数据渲染:Flutter创建商品数据模型 、请求Api接口渲染热门商品 推荐商品

    Config.dart class Config{ static String domain='http://jd.itying.com/'; } FocusModel.dart class Focu ...

  3. c# XML和实体类之间相互转换(序列化和反序列化)[砖]

    link: http://blog.okbase.net/haobao/archive/62.html by: 好饱 我们需要在XML与实体类,DataTable,List之间进行转换,下面是XmlU ...

  4. C# XML和实体类之间相互转换(序列化和反序列化)

    我们需要在XML与实体类,DataTable,List之间进行转换,下面是XmlUtil类,该类来自网络并稍加修改. using System; using System.Collections.Ge ...

  5. XML序列化反序列化—常用类

    public class XMLSerializer    {        #region (public) xml序列化        /// <summary>        /// ...

  6. XML和实体类之间相互转换(序列化和反序列化)

    我们需要在XML与实体类,DataTable,List之间进行转换,下面是XmlUtil类,该类来自网络并稍加修改. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...

  7. 用C#实现XML和实体类之间序列化和反序列化相互转换

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.I ...

  8. 对类参数的序列化和反序列化XML

    /// <summary> /// Xml序列化与反序列化 /// </summary> public class XmlUtil { #region 反序列化 /// < ...

  9. php json与xml序列化/反序列化

    在web开发中对象的序列化与反序列化经常使用,比较主流的有json格式与xml格式的序列化与反序列化,今天想写个jsop的小demo,结果发现不会使用php序列化,查了一下资料,做个笔记 简单数组js ...

随机推荐

  1. 非标准USBasp下载线烧录Arduino BootLoader的参数设置

    本文仅适用于BootLoader损坏且买到国产“免驱USBasp下载线”导致Arduino IDE无法识别从而不能烧写的情况.是一种略显非主流的操作方式. 因为Arduino的IDE并不支持这种免驱的 ...

  2. Android防止过快点击造成多次事件

    问题 onClick事件是Android开发中最常见的事件. 比方,一个submitButton.功能是点击之后会提交一个订单, 则一般代码例如以下,当中submitOrder()函数会跳转到下一页进 ...

  3. 初识ASP.net-牛腩新闻公布系统

           在做牛腩新闻公布的系统的时候,总有一种感觉就是:我仍然在敲机房收费系统,唯一不同的一点.就是敲机房收费的时候,用户界面是是自己手动画界面.而,在牛腩新闻公布系统中,用户界面,却是须要自己 ...

  4. EntityFramwork 查询

    EntityFramwork 查询 1.简单查询: SQL: SELECT * FROM [Clients] WHERE Type=1 AND Deleted=0 ORDER BY ID EF: // ...

  5. 在ios中使用单例模式编程

    本文转载至 http://blog.csdn.net/remote_roamer/article/details/7107007     1.    @implementation Singleton ...

  6. Python中的注解“@” 、Java 注解

    https://blog.csdn.net/u013474436/article/details/75675113 https://blog.csdn.net/briblue/article/deta ...

  7. 【百度之星复赛】T5 Valley Numer

    Valley Numer Problem Description 众所周知,度度熊非常喜欢数字. 它最近发明了一种新的数字:Valley Number,像山谷一样的数字. 当一个数字,从左到右依次看过 ...

  8. Python中属性

    属性定义的两种方式: 1.num1=property(GetNum,SetNum)   class Pro(): def __init__(self): self._num= def GetNum(s ...

  9. StackOver上的一个wx刷新显示的例子

    import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) self.panel = wx ...

  10. 【题解】DZY Loves Chinese

    [题解]DZY Loves Chinese II 不吐槽这题面了... 考虑如何维护图的连通性,如果把图的变成一颗的\(dfs\)生成树,那么如果把一个节点的父边和他接下来所有的返祖边删除,那么我们就 ...