首頁 >後端開發 >C#.Net教程 >C# 實體類別序列化與反序列化一 (XmlSerializer)

C# 實體類別序列化與反序列化一 (XmlSerializer)

黄舟
黄舟原創
2017-02-16 11:00:121971瀏覽

    /// <summary>
    /// 实体类序列化的反序列化的类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class EntityClassXmlSerializer<T>
    {
        /// <summary>
        /// 实体类序列化成xml string
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static string ToXMLString(T entity)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                XmlTextWriter writer = new XmlTextWriter(stream, null);
                XmlSerializer xml = new XmlSerializer(entity.GetType());
                xml.Serialize(writer, entity);
                writer.Formatting = Formatting.Indented;
                using (StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8))
                {
                    stream.Position = 0;
                    string xmlString = sr.ReadToEnd();
                    sr.Close();
                    stream.Close();
                    return xmlString;
                }
            }
        }
        /// <summary>
        /// 实体类反序列化
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T ReadFromXML(string xml)
        {
            T entity;
            byte[] byts = Encoding.UTF8.GetBytes(xml);
            using (MemoryStream stream = new MemoryStream(byts))
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));
                entity = (T)xs.Deserialize(stream);
                return entity;
            }
        }
    }


 以上就是C# 實體類序列化與反序列化一 (XmlSerializer)的內容,更多相關內容請關注PHP中文網(www.php.cn)!


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn