C# 序列化和反序列化(xml 文件)

序列化是將對象保存爲文本文件或二進制文件;json

反序列化則是讀取文件信息,還原爲對象;ide

 

序列化保存爲文本內容,主要是 xml 和 json 兩種,這裏介紹序列化爲 xml 文件的方式。spa

想要序列化,先要在類上添加 [Serializable] 特性標籤,如:3d

    [Serializable]
    public class Person {
        private string test1 = "test1";
        protected string test2 = "test2";
        public string test3 = "test3";
        internal string test4 = "test4";
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }

        public override string ToString() {
            return $"[id={id}, name={name}, age={age}, test1={test1}, test2={test2}, test4={test3}, test4={test4}]";
        }
    }

 

C# 中處理 xml 序列化的相關類都在 System.Xml.Serialization 命名空間下,這裏經過使用 XmlSerializer 類來實現序列化和反序列化:code

public class xml_serializer_manager{
    /// <summary>
    /// serialize object to xml file.
    /// </summary>
    /// <param name="path">the path to save the xml file</param>
    /// <param name="obj">the object you want to serialize</param>
    public void serialize_to_xml(string path, object obj) {
        XmlSerializer serializer = new XmlSerializer(obj.GetType());
        string content = string.Empty;
        //serialize
        using (StringWriter writer = new StringWriter()) {
            serializer.Serialize(writer, obj);
            content = writer.ToString();
        }
        //save to file
        using (StreamWriter stream_writer = new StreamWriter(path)) {
            stream_writer.Write(content);
        }
    }

    /// <summary>
    /// deserialize xml file to object
    /// </summary>
    /// <param name="path">the path of the xml file</param>
    /// <param name="object_type">the object type you want to deserialize</param>
    public object deserialize_from_xml(string path, Type object_type) {
        XmlSerializer serializer = new XmlSerializer(object_type);
        using (StreamReader reader = new StreamReader(path)) {
            return serializer.Deserialize(reader);
        }
    }
}

使用方法:xml

序列化:對象

xml_serializer_manager manager = new xml_serializer_manager();
string path = @"D:\person.xml";
Person p = new Person { id=1001, name="tommy", age=30};
manager.serialize_to_xml(path, p);

結果以下:blog

生成 person.xml 文件,並且只處理了 public 修飾的屬性,其餘都不處理get

 

反序列化:string

xml_serializer_manager manager = new xml_serializer_manager();
string path = @"D:\person.xml";
Person p = (Person)manager.deserialize_from_xml(path, typeof(Person));
Console.Write(p.ToString());

結果:

相關文章
相關標籤/搜索