XmlSerializer.cs
2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/********************************************************************************
** 类名称: XmlSerializer
** 描述 : 序列化操作对象
** 作者 : 丁书杰
** 创建时间:2018/08/10
** 版权所有 (C) :中科视语(北京)科技有限公司
*********************************************************************************/
using System;
using System.IO;
using System.Xml.Serialization;
namespace OS.Spin.Common.Files
{
public class XmlSerializer
{
public static void SaveToXml<T>(string filePath, T sourceObj)
{
try
{
if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null)
{
var type = typeof(T);
using (StreamWriter writer = new StreamWriter(filePath))
{
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(type);
XmlSerializerNamespaces nameSpace = new XmlSerializerNamespaces();
xmlSerializer.Serialize(writer, sourceObj, nameSpace);
}
}
}
catch (Exception ex)
{
LogisTrac.WriteLog(string.Format("SaveToXml:{0}", ex.Message));
}
}
public static void LoadFromXml<T>(string filePath, ref T obj)
{
try
{
object result = null;
if (File.Exists(filePath))
{
var type = typeof(T);
using (StreamReader reader = new StreamReader(filePath))
{
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(type);
result = xmlSerializer.Deserialize(reader);
}
}
obj = (T)result;
}
catch (Exception ex)
{
LogisTrac.WriteLog(string.Format("LoadFromXml:{0}", ex.Message));
}
}
}
}