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

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
    }

时间: 2024-10-11 08:08:59

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

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

直接上码: 首先创建class1类 public class Class1 { public string name { get; set; } public int age { get; set; } public bool sex { get; set; } } 实例化class1对象并进行序列化和反序列化 static void Main(string[] args) { //实例化class1类 Class1 c1 = new Class1() { name = "jia",

ASP.NET(C#) Json序列化反序列化帮助类Jsonhelper

原文地址:https://ken.io/note/csharp-asp.net-jsonhelper using System; using System.Collections.Generic; using System.Web; using System.Web.Script.Serialization; using System.Data; namespace Utils { /// <summary> /// JSON帮助类 /// </summary> public cl

Xml序列化、反序列化帮助类

之前从网络上找了一个Xml处理帮助类,并整理了一下,这个帮助类针对Object类型进行序列化和反序列化,而不需要提前定义Xml的结构,把它放在这儿供以后使用 1 /// <summary> 2 /// 功能:Xml序列化.反序列化帮助类 3 /// 说明: 4 /// 创建人: 5 /// 创建时间:2014年3月13日 6 /// </summary> 7 public static class XmlHelper 8 { 9 /// <summary> 10 ///

XML 序列化与反序列化

XML序列化与反序列化 1.将一个类转化为XML文件 /// <summary> /// 对象序列化成XML文件 /// </summary> /// <param name="type">对象类型</param> /// <param name="obj">对象</param> /// <param name="fileName">序列化的XML文件路径<

c# XML序列化与反序列化 属性字段标识

序列化对象 public class People { [XmlAttribute("NAME")] public string Name { set; get; } [XmlAttribute("AGE")] public int Age { set; get; } } [XmlRoot("Root")] public class Student : People { [XmlElement("CLASS")] public

c# xml序列化和反序列化。也就是xml的解析和反解析。

用习惯了newTownSoft.json 的json反序列化.碰到xml是真的不习惯. 每次json反序列化都是直接把json丢到bejson网站生成一个实体类,稍微修改修改一点点变量名.然后直接newTownSoft反序列化,一下就得到一个实体类了.今天调某个接口,碰到xml. 记录如下. xml <response> <functionID>setItemsPics</functionID> <time>2017-09-07 15:51:04</t

XML序列化与反序列化+自定义XML注解框架XmlUtils

背景 前面一篇总结了Serializable的序列化与反序列化,现在接着总结XML.主要内容:XML基本的序列化与反序列化方法.一些注意事项.以及自定义了一个XML注解框架(简洁代码,解放双手). XML的序列化与反序列化 先与Serializable进行简单的对比: Serializable存储的文件,打开后无法正常查看,安全性高.xml文件可通过文本编辑器查看与编辑,可读性高(浏览器会格式化xml文件,更方便查看),安全性低: Serializable文件通过了签名,只能在自己的程序中反序列

[.net 面向对象程序设计进阶] (11) 序列化(Serialization)(三) 通过接口IXmlSerializable实现XML序列化及XML通用类

[.net 面向对象程序设计进阶] (11) 序列化(Serialization)(三) 通过接口IXmlSerializable实现XML序列化及XML通用类 本节导读:本节主要介绍通过序列化接口IXmlSerializable实现XML序列化和反序列化,整理了XML基础操作及序列化的通用类(包括XML及节点的基础读写操作,XML到DataSet\DataTable互转换操作,XML序列化及反序列化通用方法等). 读前必备: A.类和类的实例 [.net 面向对象编程基础]  (9) 类和类的

C#实现接口xml序列化与反序列化

C#中接口无法被xml序列化,提示不支持.百度和bing也搜不到,只好自己动手写了 原理上肯定支持,.Net自己的xml序列化有一个IXmlSerializable接口. 自行实现该接口,并取得实现改接口的类,再进行自定义的序列化处理即可. using System.Collections; using System.Xml.Serialization; using System; using System.Xml; [XmlRoot("SerInterface"), Serializ