序列化及反序列化 一個對像

Type type = typeof(MDLot[]);
MDLot[] lots = (MDLot[])XMLHelper.DeSerializeXML(strXML, type); //反序列化一個對像數組;   strXML為要序列化的字符串

Type type = typeof(List<HSWMS.ModelDomain.GoodsIssue>);
modelGoodsIssueList = (List<HSWMS.ModelDomain.GoodsIssue>)XMLHelper.DeSerializeXML(ParameterXML, type);       //反序列化一個對像數組; ParameterXML為要序列化的字符串

Type type = typeof(ModelDomain.PaperRequisition);
modelPaperRequisition = (ModelDomain.PaperRequisition)XMLHelper.DeSerializeXML(PaperRequisitionXml, type);      //反序列化一個對像;   PaperRequisitionXml為要序列化的字符串

string xml = XMLHelper.SerializeXML(Info);   //序列化成XML字符串

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace Utility
{
    public static class XMLHelper
    {
        /// <summary>
        /// 反序列化为一个类
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object DeSerializeXML(string xml, Type type)
        {
            object obj = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer(type);
                byte[] list = Encoding.UTF8.GetBytes(xml);
                MemoryStream stream = new MemoryStream(list);
                obj = serializer.Deserialize(stream);
            }
            catch (Exception ex)
            {
                throw ex;

            }
            return obj;
        }

        /// <summary>
        /// 将对象序列化为xml文档
        /// 1.如果对象中包含引用类型的属性,如果引用类型为Null,那么此属性不会被序列化为一个Attribute
        /// 2.如果此引用类型只构造,里面的内容没有赋值,那么序列化为类似为

        /// 3.如果标记为[XmlIgnore]将不被序列化为XML属性

        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string SerializeXML(object data)
        {
            string ret = string.Empty;
            if (data != null)
            {
                XmlSerializer serializer =
                    new XmlSerializer(data.GetType());
                MemoryStream stream = new MemoryStream();
                serializer.Serialize(stream, data);
                ret = Encoding.UTF8.GetString(stream.ToArray());
            }
            return ret;
        }
    }
}

原文地址:https://www.cnblogs.com/guyuehuanhuan/p/1948142.html