本文實(shí)例為大家分享了C#實(shí)現(xiàn)XML文件讀取的具體代碼,供大家參考,具體內(nèi)容如下
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
|
using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml.Serialization; /// <summary> /// 工具類 /// </summary> public static class Tools { /// <summary> /// 存儲數(shù)據(jù) UTF8 /// </summary> /// <param name="data">數(shù)據(jù),自定義類</param> public static void SaveData(GameData data) { string fileName = Consts.DataPath; // 文件名 // 文件流 Stream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter sw = new StreamWriter(stream, Encoding.UTF8); // UTF8 XmlSerializer xmlSerializer = new XmlSerializer(data.GetType()); // XML 文件序列化 xmlSerializer.Serialize(sw, data); sw.Close(); stream.Close(); } /// <summary> /// 讀取數(shù)據(jù) /// </summary> /// <returns>讀取獲得的數(shù)據(jù)</returns> public static GameData GetDataWithOutBom() { GameData data = new GameData(); Stream stream = new FileStream(Consts.DataPath, FileMode.Open, FileAccess.Read); // 忽略標(biāo)記 true StreamReader sr = new StreamReader(stream, true ); XmlSerializer xmlSerializer = new XmlSerializer(data.GetType()); data = xmlSerializer.Deserialize(sr) as GameData; sr.Close(); stream.Close(); return data; } } |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/coderJiebao/archive/2018/04/08/CSharp06.html