提供一个类可以实现将类序列化为xml

来源:互联网 发布:2016知乎年度吐槽精选 编辑:程序博客网 时间:2024/05/21 05:59

仅供参考:

auther:king

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

 

    /// <summary>
    /// ObjectToXml
    /// </summary>
    public class ObjectToXml
    {
        /// <summary>
        ///  Serialize Current Object To Xml Format
        /// </summary>
        /// <returns>Input: Xml Format String</returns>
        public string SerializeToXml()
        {
            StringBuilder strBuilder = new StringBuilder();
            try
            {
                XmlSerializer serializer = new XmlSerializer(this.GetType());
                TextWriter writer = new StringWriter(strBuilder);
                serializer.Serialize(writer, this);
            }catch(Exception e)
            {
                throw new Exception("Error:",e);
            }

            return strBuilder.ToString();
        }

        /// <summary>
        /// DeSerialize Xml To Object
        /// </summary>
        /// <param name="source">Input: Xml Format String</param>
        /// <returns>Object</returns>
        public ObjectToXml XmlToObject(string source)
        {
            ObjectToXml target = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer(this.GetType());
                TextReader reader = new StringReader(source);
                target = serializer.Deserialize(reader) as ObjectToXml;
            }
            catch(Exception e)
            {
                throw new Exception("Error:", e);
            }

            return target;
        }
    }

原创粉丝点击