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; }
    }
}

作者最新文章
C# 使用 CSVHelper 操作 csv 文件, .net core, .net framework 读取写入 csv 文件
C# 实现字符串文本换行的方法,文本如何换行
C# 如何循环读取文件每一行文本内容
C# DateTime AddMonths 的错误用法导致跳过日期
C# 全角转换半角,半角转换为全角