- XML反序列读取(只存储有标记的属性)
点击查看代码
public static class Util
{
public static void SerializeToXml<T>(T objectToSerialize, string path)
{
try
{
// 创建 DataContractSerializer 实例
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
var dir = Path.GetDirectoryName(path);
Directory.CreateDirectory(dir);
using (MemoryStream ms = new MemoryStream())
{
using (XmlWriter writer = XmlWriter.Create(ms, new XmlWriterSettings { Encoding = Encoding.UTF8 }))
{
serializer.WriteObject(writer, objectToSerialize);
}
ms.Seek(0, SeekOrigin.Begin); // 重置流的位置到开头
using (XmlReader reader = XmlReader.Create(ms))
{
// 使用XDocument作为中间步骤来加载XML,然后转换为XmlDocument
XDocument xDoc = XDocument.Load(reader);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xDoc.CreateReader());
if (File.Exists(path))
{
File.Delete(path);
}
xmlDoc.Save(path);
}
}
}
catch (Exception ex)
{
throw new Exception($"Fail To Save, [{path}]。", ex);
}
}
public static T DeserializeFromXml<T>(string path)
{
try
{
// 创建 DataContractSerializer 实例
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
// 反序列化 XML 为 MyClass 对象(可选)
T deserializedObject;
using (XmlReader reader = XmlReader.Create(path))
{
deserializedObject = (T)serializer.ReadObject(reader);
}
return deserializedObject;
}
catch (Exception ex)
{
throw new Exception($"Fail To Deserialize, [{path}]。", ex);
}
}
}
点击查看代码
[DataContract]
public class Heater
{
[DataMember]
public double TargetTemperature { get; set; }
[DataMember]
public bool Enable { get; set; } = true;
}
[DataContract]
public class HeaterManager
{
private readonly List<IHeater> heaters;
private readonly string savePath;
public HeaterManager(IHeater[] heaters)
{
this.heaters = new List<IHeater>(heaters);
this._alarmBus = alarmBus;
this.log = LogManager.GetLogger("OperationLogger");
this.savePath = Path.Combine(PathManager.DataProjectPath, $"Heaters.xml");
if (File.Exists(this.savePath))
{
var hm = Domain.Util.DeserializeFromXml<HeaterManager>(this.savePath);
var heaterDatas = hm.HeaterDatas;
foreach (var heater in heaters)
{
var data = heaterDatas.Find(x => x.Name == heater.Name);
if (data != null)
{
heater.TargetTemperature = data.TargetTemperature;
}
}
}
else
{
this.HeaterDatas = new List<Heater>();
foreach (var heater in heaters)
{
this.HeaterDatas.Add(heater as Heater);
}
this.Save();
}
}
[DataMember]
public List<Heater> HeaterDatas { get; set; }
public IEnumerable<IHeater> Heaters => this.heaters;
public void Save()
{
Util.SerializeToXml(this, this.savePath);
}
}
2、XML反序列读取(列表类中所有属性保存)
点击查看代码
public class Class_to_xml
{
//实体类转换XML,xml序列化
public static string XmlSerialize<T>(T obj)
{
using (StringWriter sw = new StringWriter())
{
Type t = obj.GetType();
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(sw, obj);
sw.Close();
return sw.ToString();
}
}
//xml反序列化
public static T DESerializer<T>(string strXML) where T : class
{
try
{
using (StringReader sr = new StringReader(strXML))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(sr) as T;
}
}
catch (Exception ex)
{
return null;
}
}
}
用法
点击查看代码
#region 列表集合
//测试集合
List<Student> list = new List<Student>()
{
new Student(){Id=1,Name="小红",Sex='2',Age=20},
new Student(){Id=2,Name="小明",Sex='1',Age=22},
new Student(){Id=3,Name="小王",Sex='1',Age=19},
new Student(){Id=4,Name="测试",Sex='2',Age=23}
};
//序列化为xml
string strXML = Class_to_xml.XmlSerialize<List<Student>>(list);
Console.Write(strxml);
//反序列化为list
List<Student> listStu = Class_to_xml.DESerializer<List<Student>>(strXML);
foreach (var item in listStu)
{
Console.WriteLine(item.Age);
}
#endregion