C#序列化和反序列化(xml⽂件)
序列化是将对象保存为⽂本⽂件或⼆进制⽂件;
反序列化则是读取⽂件信息,还原为对象;
序列化保存为⽂本内容,主要是 xml 和 json 两种,这⾥介绍序列化为 xml ⽂件的⽅式。
想要序列化,先要在类上添加 [Serializable] 特性标签,如:
[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 类来实现序列化和反序列化: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);
}
python处理xml文件
}
}
使⽤⽅法:
序列化:
xml_serializer_manager manager = new xml_serializer_manager();
string path = @"D:\l";
Person p = new Person { id=1001, name="tommy", age=30};
manager.serialize_to_xml(path, p);
结果如下:
⽣成 l ⽂件,⽽且只处理了 public 修饰的属性,其他都不处理
反序列化:
xml_serializer_manager manager = new xml_serializer_manager(); string path = @"D:\l";
Person p = (Person)manager.deserialize_from_xml(path, typeof(Person)); Console.Write(p.ToString());
结果:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。