首页 > 代码库 > XML转换为对象操作类详解

XML转换为对象操作类详解

//XML转换为对象操作类
//一,XML与Object转换类

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace WebApplication1
{
    public sealed class XMLSerilizable
    {
        /// <summary>
        /// 将object对象序列化成XML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string ObjectToXML<T>(T t, Encoding encoding)
        {
            XmlSerializer ser = new XmlSerializer(t.GetType());
            using (MemoryStream mem = new MemoryStream())
            {
                using (XmlTextWriter writer = new XmlTextWriter(mem, encoding))
                {
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    ns.Add("", "");
                    ser.Serialize(writer, t, ns);
                    return encoding.GetString(mem.ToArray()).Trim();
                }
            }
        }

        /// <summary>
        /// 将XML反序列化成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static T XMLToObject<T>(string source, Encoding encoding)
        {
            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            using (MemoryStream stream = new MemoryStream(encoding.GetBytes(source)))
            {
                return (T)mySerializer.Deserialize(stream);
            }
        }

        /// <summary>
        /// 二进制方式序列化对象
        /// </summary>
        /// <param name="testUser"></param>
        public static string Serialize<T>(T obj)
        {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            return ms.ToString();
        }

        /// <summary>
        /// 二进制方式反序列化对象
        /// </summary>
        /// <returns></returns>
        public static T DeSerialize<T>(string str) where T : class
        {
            MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(str));
            BinaryFormatter formatter = new BinaryFormatter();
            T t = formatter.Deserialize(ms) as T;
            return t;
        }

    }
}

 

//二,测试类

using System;
using System.Xml.Serialization;

namespace WebApplication1
{
    [Serializable]
    [XmlRoot("Result")]
    public class XMLClass
    {
        private string rtnValue;
        [XmlElement("Value")]
        public string RtnValue
        {
            get { return rtnValue; }
            set { rtnValue =http://www.mamicode.com/ value; }
        }
        private string rtnKey;
        [XmlElement("Key")]
        public string RtnKey
        {
            get { return rtnKey; }
            set { rtnKey = value; }
        }
    }
}

//三,调用

 

using System;
using System.Text;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            XMLClass xc = new XMLClass();
            xc.RtnKey = "TestXML";
            xc.RtnValue = "ObjectToXML";
            string xml = XMLSerilizable.ObjectToXML<XMLClass>(xc,System.Text.Encoding.UTF8);

            StringBuilder strXML = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            strXML.Append("<Result>");
            strXML.AppendFormat("<Key>{0}</Key>","TestXML");
            strXML.AppendFormat("<Value>{0}</Value>","XMLToObject");
            strXML.Append("</Result>");

            XMLClass xClass = XMLSerilizable.XMLToObject<XMLClass>(strXML.ToString(),System.Text.Encoding.UTF8);
        }
    }
}

 

XML转换为对象操作类详解