public class XMLSerializer
    {
        #region (public) xml序列化
        /// <summary>
        /// xml序列化
        /// </summary>
        /// <param name="obj">obj类</param>
        /// <returns>string字符串</returns>
        public static string XMLSerialize(object obj)
        {
            XmlSerializer xs = new XmlSerializer(obj.GetType());
            StringBuilder strBuidler = new StringBuilder();
            XmlWriterSettings setting = new XmlWriterSettings();
            setting.OmitXmlDeclaration = true;//去掉xml版本声明
            System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(strBuidler, setting);
            XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
            xmlns.Add(string.Empty, string.Empty);
            xs.Serialize(xw, obj, xmlns);
            xw.Close();
            return strBuidler.ToString();
        }
        #endregion

#region (public) xml序列化
        /// <summary>
        /// xml序列化
        /// </summary>
        /// <param name="obj">obj类</param>
        /// <returns>string字符串</returns>
        public static string ConvertToString(object objectToConvert)
        {
            string xml = null;
            if (objectToConvert == null)
                return xml;

Type t = objectToConvert.GetType();

XmlSerializer ser = new XmlSerializer(t);
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
            {
                ser.Serialize(writer, objectToConvert, ns);
                xml = writer.ToString();
                writer.Close();
            }
            return xml;
        }
        #endregion

#region (public) xml反序列化
        /// <summary>
        /// xml反序列化
        /// </summary>
        /// <param name="s">字符串string</param>
        /// <param name="type">obj type</param>
        /// <returns>obj</returns>
        public static object XMLDeserialize(string s, Type type)
        {

XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(s);
            s = xmlDoc.DocumentElement.OuterXml;
            XmlSerializer xs = new XmlSerializer(type);
            Stream stream = new System.IO.MemoryStream(System.Text.ASCIIEncoding.UTF8.GetBytes(s));
            object obj = xs.Deserialize(stream);
            stream.Close();
            return obj;
        }
        #endregion

#region (public) xml反序列化

/// <summary>
        /// xml to dataset
        /// </summary>
        /// <param name="xmlData">xml字符串</param>
        /// <returns>dataset</returns>
        public static DataSet XML2DataSet(string xmlData)
        {
            StringReader stream = null;
            XmlTextReader reader = null;
            try
            {
                DataSet xmlDS = new DataSet();
                stream = new StringReader(xmlData);
                reader = new XmlTextReader(stream);
                xmlDS.ReadXml(reader);
                return xmlDS;
            }
            catch (Exception ex)
            {
                string strTest = ex.Message;
                return null;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
        }
        #endregion

#region (public) XML反序列化
        /// <summary>
        /// 读取文件转化为对象
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="objectType">对象类型</param>
        /// <returns>对象</returns>
        public static object ConvertFileToObject(string path, Type objectType)
        {
            object convertedObject = null;

if (path != null && path.Length > 0)
            {
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    XmlSerializer ser = new XmlSerializer(objectType);
                    convertedObject = ser.Deserialize(fs);
                    fs.Close();
                }
            }
            return convertedObject;
        }
        #endregion

#region (public) xml 反序列化
        /// <summary>
        /// 将xml字符串转换为对应的实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="xmlDocument">xml字符串</param>
        /// <returns>实体类型对象</returns>
        public static T ConvertXmlToObject<T>(string xml) where T : class, new()
        {
            if (string.IsNullOrEmpty(xml)) return new T();
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            T resultObject;
            using (TextReader reader = new StringReader(xml))
            {
                resultObject = (T)serializer.Deserialize(reader);
            }
            return resultObject;
        }

#endregion

#region(public) 对象保存为xml
        /// <summary>
        ///  把对象序列化为XML 并保存为文件
        /// </summary>
        /// <param name="objectToConvert">对象</param>
        /// <param name="path">路径</param>
        public static void SaveAsXML(object objectToConvert, string path)
        {
            if (objectToConvert != null)
            {
                Type t = objectToConvert.GetType();
                XmlSerializer ser = new XmlSerializer(t);
                using (StreamWriter writer = new StreamWriter(path))
                {
                    ser.Serialize(writer, objectToConvert);
                    writer.Close();
                }
            }
        }
        #endregion
    }

XML序列化反序列化—常用类的更多相关文章

  1. .NET中XML序列化和反序列化常用类和用来控制XML序列化的属性总结(XmlSerializer,XmlTypeAttribute,XmlElementAttribute,XmlAttributeAttribute,XmlArrayAttribute...)

    序列化和反序列化是指什么? 序列化(seriallization): 将对象转化为便于传输的数据格式, 常见的序列化格式:二进制格式,字节数组,json字符串,xml字符串.反序列化(deserial ...

  2. C# XML序列化/反序列化参考

    .NET提供了很不错的XML序列化/反序列化器,(它们所在的命名空间为System.Xml.Serialization)这是很方便的,下面对它的使用做一些总结,以供参考. 1,简单序列化 public ...

  3. C# Json库 和 xml 序列化反序列化 存在的问题

    json 正常情况下不会对私有成员进行序列化和反序列化, 因此在用json做深拷贝时, 就会丢失数据. 解决办法:       声明成公有成员. json在序列化和反序列化时, 如果类中有IComma ...

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

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

  5. .NET(C#):XML序列化时派生类的处理

    原文 www.cnblogs.com/mgen/archive/2011/12/03/2275014.html 目录 1. 针对基类的XmlSerializer序列化派生类 2. 类内成员是派生类的序 ...

  6. C# 复杂格式多级深度XML序列化反序列化

     default.xml 文件如下: <config><partnerships>  <partnership name="Main_Listener" ...

  7. C# XML序列化/反序列化类XmlSerializer使用示例

    using System; using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization; ...

  8. XML序列化/反序列化数据库形式保存和读取。

    直接上码: 首先创建class1类 public class Class1 { public string name { get; set; } public int age { get; set; ...

  9. XML序列化反序列化

    using System; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; nam ...

随机推荐

  1. shapefile 编码错误问题解决 Wrong codepage of shapefile Warning 1: One or several characters couldn't be converted correctly from UTF-8 to ISO-8859-1.

    linux下运行,因为大部分shapefile 文件,在使用时都没有指定字符集,所以qgis只能从环境变量中获取设置环境变量中获取SHAPE_ENCODING. 目前唯一的解决办法就是设置环境变量 $ ...

  2. OGR API Tutorial

    This document is intended to document using the OGR C++ classes to read and write data from a file. ...

  3. java字符操作获取汉字的拼音以及其它经常使用工具

    公司需求年年有,今年有点小特殊,哈哈. 忽然加了个需求,说要实现汉字转拼音查询. 在努力下写出来了,如今分享一下吧!.! /** * 汉字转拼音缩写 * * @param str * 要转换的汉字字符 ...

  4. java模拟实现生产者---消费者问题

    本文章为小编原创,请尊重文章的原创性,转载请注意写明转载来源:http://blog.csdn.net/u012116457 已知技术參数: 生产者消费者问题,描写叙述一组生产者向一组消费者提供产品/ ...

  5. c语言,数据类型转换

    在执行算术运算时,计算机比C语言的限制更多.为了让计算机执行算术运算,通常要求操作数有相同的大小(即位的数量相同),并且要求存储的方式也相同.计算机可能可以直接将两个16位整数相加,但是不能直接将16 ...

  6. EL显示List里嵌套map(Spring MVC3)返回的model

    <c:forEach items="${requestScope.courseList}" var="cMap" varStatus="stat ...

  7. KMP算法 KMP模式匹配 一(串)

    A - KMP模式匹配 一(串) Crawling in process... Crawling failed Time Limit:1000MS     Memory Limit:131072KB  ...

  8. Qt的setMouseTracking使用

    bool mouseTracking 这个属性保存的是窗口部件跟踪鼠标是否生效. 如果鼠标跟踪失效(默认),当鼠标被移动的时候只有在至少一个鼠标按键被按下时,这个窗口部件才会接收鼠标移动事件. 如果鼠 ...

  9. 在chrome中使用axure生成原型的问题

    来自:非原型不设计

  10. 一道c++小编程题,

    题目: 编写一个小程序,从标准输入读入一系列string对象,寻找连续重复出现的单词,程序应该找出满足以下条件的单词的输入位置:该单词的后面紧跟着再次出现自己本身,跟 踪重复次数量多的单词及其重复次数 ...