数据持久化
数据持久化是指将应用程序中的临时数据(如游戏进度、玩家设置等)永久保存到存储设备(硬盘、SD卡等)中的过程,以便在应用程序关闭后再次启动时能够恢复这些数据。

Xml

固定语法
1
| <?xml version="1.0" encoding="UTF-8"?>
|


在C#中读取XML文件的方法
在C#中,你可以使用多种方式读取XML文件。以下是几种常用的方法:
1. 使用XmlDocument类(传统方式)
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
| using System.Xml;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("path/to/your/file.xml");
XmlNode root = xmlDoc.DocumentElement;
foreach (XmlNode node in root.ChildNodes) { Console.WriteLine($"节点名: {node.Name}"); Console.WriteLine($"节点值: {node.InnerText}"); if (node.Attributes != null) { foreach (XmlAttribute attr in node.Attributes) { Console.WriteLine($"属性: {attr.Name} = {attr.Value}"); } } }
|
2. 使用XDocument类(LINQ to XML,推荐方式)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| using System.Xml.Linq;
XDocument xdoc = XDocument.Load("path/to/your/file.xml");
XElement root = xdoc.Root;
var elements = from el in root.Elements() select el;
foreach (XElement el in elements) { Console.WriteLine($"元素名: {el.Name}"); Console.WriteLine($"元素值: {el.Value}"); foreach (XAttribute attr in el.Attributes()) { Console.WriteLine($"属性: {attr.Name} = {attr.Value}"); } }
|
3. 使用XmlReader类(流式读取,适合大文件)
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
| using System.Xml;
using (XmlReader reader = XmlReader.Create("path/to/your/file.xml")) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { Console.WriteLine($"节点名: {reader.Name}"); if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { Console.WriteLine($"属性: {reader.Name} = {reader.Value}"); } reader.MoveToElement(); } } else if (reader.NodeType == XmlNodeType.Text) { Console.WriteLine($"节点值: {reader.Value}"); } } }
|
4. 反序列化为对象(推荐用于结构化数据)
首先定义一个与XML结构对应的类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| [Serializable] [XmlRoot("Root")] public class MyData { [XmlElement("Item")] public List<Item> Items { get; set; } }
public class Item { [XmlAttribute("id")] public int Id { get; set; } [XmlElement("Name")] public string Name { get; set; } [XmlElement("Value")] public string Value { get; set; } }
|
然后使用XmlSerializer反序列化:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| using System.Xml.Serialization;
XmlSerializer serializer = new XmlSerializer(typeof(MyData));
using (FileStream stream = new FileStream("path/to/your/file.xml", FileMode.Open)) { MyData data = (MyData)serializer.Deserialize(stream); foreach (var item in data.Items) { Console.WriteLine($"ID: {item.Id}, Name: {item.Name}, Value: {item.Value}"); } }
|