代码段——XML序列化、反序列化辅助类

1.创建辅助类XmlSerializationHelper

 public static class XmlSerializationHelper
 {
     /// <summary>
     /// 将对象序列化为XML字符串。
     /// </summary>
     /// <typeparam name="T">要序列化的对象类型。</typeparam>
     /// <param name="obj">要序列化的对象。</param>
     /// <param name="omitXmlDeclaration">是否省略XML声明,默认为true。</param>
     /// <param name="omitNamespaces">是否省略命名空间,默认为true。</param>
     /// <returns>序列化后的XML字符串。</returns>
     /// <exception cref="ArgumentNullException">如果对象为null,则抛出此异常。</exception>
     public static string SerializeToXml<T>(T obj, bool omitXmlDeclaration = true, bool omitNamespaces = true)
     {
         if (obj == null)
         {
             throw new ArgumentNullException(nameof(obj), "The object to serialize cannot be null.");
         }

         XmlSerializer serializer = new XmlSerializer(typeof(T));

         // 创建一个XmlSerializerNamespaces对象,并根据参数决定是否添加空的命名空间
         XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
         if (omitNamespaces)
         {
             namespaces.Add("", ""); // 添加一个空的命名空间
         }

         using (StringWriter writer = new StringWriter())
         {
             // 使用XmlWriterSettings来控制XML声明
             XmlWriterSettings settings = new XmlWriterSettings();
             settings.OmitXmlDeclaration = omitXmlDeclaration; // 控制是否省略XML声明
             settings.Indent = true;//自动缩进

             using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings))
             {
                 serializer.Serialize(xmlWriter, obj, namespaces);
             }

             return writer.ToString();
         }
     }

     /// <summary>
     /// 将XML字符串反序列化为对象。
     /// </summary>
     /// <typeparam name="T">要反序列化的对象类型。</typeparam>
     /// <param name="xml">要反序列化的XML字符串。</param>
     /// <returns>反序列化后的对象。</returns>
     /// <exception cref="ArgumentNullException">如果XML字符串为null或空,则抛出此异常。</exception>
     public static T DeserializeFromXml<T>(string xml)
     {
         if (string.IsNullOrEmpty(xml))
         {
             throw new ArgumentNullException(nameof(xml), "The XML string to deserialize cannot be null or empty.");
         }

         XmlSerializer serializer = new XmlSerializer(typeof(T));

         using (StringReader reader = new StringReader(xml))
         {
             return (T)serializer.Deserialize(reader);
         }
     }
 }

2.演示

  • 定义实体类
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public List<string> Hobbies { get; set; }
        public Address StudentAddress { get; set; }
        public List<Course> ListCourse { get; set; }
    }

    [XmlType("Address")]
    public class Address
    {
        [XmlAttribute("Code", DataType = "int")]
        public int Code { get; set; }

        [XmlAttribute("Region")]
        public string Region { get; set; }

        [XmlAttribute("City")]
        public string City { get; set; }

        [XmlAttribute("Province")]
        public string Province { get; set; }

        [XmlIgnore]
        public string Country { get; set; }
    }

    [XmlType("Course")]
    public class Course
    {
        [XmlElement("CourseId")]
        public int CourseId { get; set; }

        [XmlElement("CourseName")]
        public string CourseName { get; set; }
    }
  • 测试序列化和反序列化
        private static void Main(string[] args)
        {
            Student student = new Student()
            {
                Id = 1,
                Age = 30,
                Name = "Tom",
                Hobbies = new List<string>() { "Baskball", "Football" },
                StudentAddress = new Address() { Code = 1, Region = "HuoDong", Province = "JiangSu", City = "Suzhou", Country = "China" },
                ListCourse = new List<Course>() { new Course() { CourseId = 100, CourseName = "Chinese" }, new Course() { CourseId = 101, CourseName = "Math" } }
            };

            string xmlStudent = XmlSerializationHelper.SerializeToXml(student);

            Student student2 = XmlSerializationHelper.DeserializeFromXml<Student>(xmlStudent);

            Console.ReadKey();
        }

序列化结果:

<Student>
  <Id>1</Id>
  <Name>Tom</Name>
  <Age>30</Age>
  <Hobbies>
    <string>Baskball</string>
    <string>Football</string>
  </Hobbies>
  <StudentAddress Code="1" Region="HuoDong" City="Suzhou" Province="JiangSu" />
  <ListCourse>
    <Course>
      <CourseId>100</CourseId>
      <CourseName>Chinese</CourseName>
    </Course>
    <Course>
      <CourseId>101</CourseId>
      <CourseName>Math</CourseName>
    </Course>
  </ListCourse>
</Student>
posted @   shanzm  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2020-02-11 .NET异步程序设计——异步委托
2019-02-11 《SQL CookBook 》笔记-第二章-查询结果排序
TOP
点击右上角即可分享
微信分享提示