C# entity class serialization and deserialization 1 (XmlSerializer)

黄舟
Release: 2017-02-16 11:00:12
Original
1937 people have browsed it

    /// <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;
            }
        }
    }
Copy after login


The above is the content of C# entity class serialization and deserialization (XmlSerializer). For more related content, please pay attention to PHP Chinese website (www.php.cn)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!