C# Xml字符串与实体Model之间相互转换, 序列化, 反序列化

C# Xml字符串与实体Model之间相互转换, 序列化, 反序列化
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApp34
{
    class Program
    {
        static void Main(string[] args)
        {
            Student student = new Student();
            student.Name = "张三";
            student.Age = "18";

            // 序列化
            string xml = XmlSerialize<Student>(student);
            /*
                <?xml version="1.0"?>
                <student xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                  <name>张三</name>
                  <age>18</age>
                </student>   
             */

            // 反序列化
            Student xml2Model= XmlDeserialize<Student>(xml);
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string XmlSerialize<T>(T obj)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    XmlSerializer serializer = new XmlSerializer(obj.GetType());
                    serializer.Serialize(ms, obj);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T XmlDeserialize<T>(string xml) where T : class
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(sr) as T;
                }
            }
            catch
            {
                throw;
            }
        }
    }

    /// <summary>
    /// 学生
    /// </summary>
    [XmlRoot("student")]
    public class Student
    {
        /// <summary>
        /// 姓名 
        /// </summary>
        [XmlElement(ElementName = "name")]
        public string Name { get; set; }

        /// <summary>
        /// 年龄
        /// </summary>
        [XmlElement(ElementName = "age")]
        public string Age { get; set; }
    }
}

作者最新文章
ASP.NET aspx获取服务器信息, 操作系统, .NET版本, IIS版本
C# Unix转换本地时间, Unix时间戳转换DateTime
C# 获取Unix时间戳
C# DateTime.Ticks 转换为 DateTime
C# 数字转换字符串左边补0, 数字前补0的方法