.NET Core C# XML序列化与反序列化

序列化是指将对象转换为字节序列的过程,反序列化是指将字节序列转换为对象的过程。

贴出实体类和工具类代码,在想使用的地方直接调用工具类

{
    [XmlType("Person")]
    public class Person
    {
        /// 
        /// 姓名
        /// 
        [XmlElement("name")]
        [Required]
        [StringLength(20)]
        public string Name{ get; set; }

        /// 
        /// 年龄
        /// 
        [XmlElement("age")]
        [Required]
        public int Age{ get; set; }
    }
public class XmlConverter
    {
        public static string Serialize(T obj)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
            serializer.Serialize(writer, obj);
            string xml = writer.ToString();
            writer.Close();
            writer.Dispose();

            return xml;
        }

        public static T Deserialize(string xml)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            StringReader reader = new StringReader(xml);
            T result = (T)(serializer.Deserialize(reader));
            reader.Close();
            reader.Dispose();

            return result;
        }
    }

 

你可能感兴趣的:(.net,core,.ne,core,C#,xml,Serialize,Deserialize)