|
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102 |
using
UnityEngine; using
System.Collections; using
System.Xml; using
System.Xml.Serialization; using
System.IO;using
System.Text;/// <summary>/// 持久化工具类/// </summary>public
class Persistence : MonoBehaviour { //持久化文件路径 static
string FileLocation = Application.dataPath + "//StreamingAssets//Xml//Persistence//"; /// <summary> /// 保存数据到XML /// </summary> public
static void Save(string
fileName, object
obj){ CreateXML(fileName,SerializeObject(obj)); } /// <summary> /// 加载XML数据 /// </summary> public
static object Load(string
fileName, System.Type type){ return
DeserializeObject(type,LoadXML(fileName)); } /// <summary> /// 序列化对象 /// </summary> public
static string SerializeObject(object
pObject) { string
XmlizedString = null; MemoryStream memoryStream = new
MemoryStream(); XmlSerializer xs = new
XmlSerializer(pObject.GetType()); XmlTextWriter xmlTextWriter = new
XmlTextWriter(memoryStream, Encoding.UTF8); xs.Serialize(xmlTextWriter, pObject); memoryStream = (MemoryStream)xmlTextWriter.BaseStream; XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray()); return
XmlizedString; } /// <summary> /// 反序列化对象 /// </summary> public
static object DeserializeObject(System.Type type,string
pXmlizedString) { XmlSerializer xs = new
XmlSerializer(type); MemoryStream memoryStream = new
MemoryStream(StringToUTF8ByteArray(pXmlizedString)); XmlTextWriter xmlTextWriter = new
XmlTextWriter(memoryStream, Encoding.UTF8); return
xs.Deserialize(memoryStream); } /// <summary> /// 将二进制转换为字符串 /// </summary> public
static string UTF8ByteArrayToString(byte[] characters) { UTF8Encoding encoding = new
UTF8Encoding(); string
constructedString = encoding.GetString(characters); return
(constructedString); } /// <summary> /// 将字符串转换为二进制 /// </summary> public
static byte[] StringToUTF8ByteArray(string
pXmlString) { UTF8Encoding encoding = new
UTF8Encoding(); byte[] byteArray = encoding.GetBytes(pXmlString); return
byteArray; } /// <summary> /// 创建XML文件 /// </summary> public
static void CreateXML(string
fileName,string
dataStr) { StreamWriter writer; FileInfo t = new
FileInfo(FileLocation+"//"+ fileName + ".xml"); if(!t.Exists){ writer = t.CreateText(); }else{ t.Delete(); writer = t.CreateText(); } writer.Write(dataStr); writer.Close(); } /// <summary> ///加载XML文件 /// </summary> public
static string LoadXML(string
fileName) { StreamReader r = File.OpenText(FileLocation+"//"+ fileName + ".xml"); string
info = r.ReadToEnd(); r.Close(); return
info; }} |
原文:http://www.cnblogs.com/xiao-wei-wei/p/3547354.html