Unity XML3——XML序列化

news/2024/5/18 23:29:42

一、XML 序列化

​ 序列化:把对象转化为可传输的字节序列过程称为序列化,就是把想要存储的内容转换为字节序列用于存储或传递

​ 反序列化:把字节序列还原为对象的过程称为反序列化,就是把存储或收到的字节序列信息解析读取出来使用

(一)XML 序列化

1.准备数据结构

public class Lesson1Test
{public    int          testPublic    = 10;private   int          testPrivate   = 11;protected int          testProtected = 12;internal  int          testInternal  = 13;public    string       testPUblicStr = "123";public    int          testPro { get; set; }public    Lesson1Test2 testClass = new Lesson1Test2();public    int[]        arrayInt  = new int[3] { 5, 6, 7 };public    List<int> listInt = new List<int>() { 1, 2, 3, 4 };public    List<Lesson1Test2> listItem = new List<Lesson1Test2>() { new Lesson1Test2(), new Lesson1Test2() };// 不支持字典// public Dictionary<int, string> testDic = new Dictionary<int, string>() { { 1, "123" } };
}public class Lesson1Test2
{public int test1 = 1;public float test2 = 1.1f;public bool test3 = true;
}Lesson1Test lt = new Lesson1Test();

2.进行序列化

XmlSerializer:用于序列化对象为 xml 的关键类

StreamWriter:用于存储文件

using:用于方便流对象释放和销毁

using System.Xml.Serialization;// 第一步:确定存储路径
string path = Application.persistentDataPath + "/Lesson1Test.xml";// 第二步:结合 using知识点 和 StreamWriter这个流对象 来写入文件
// 括号内的代码:写入一个文件流 如果有该文件 直接打开并修改 如果没有该文件 直接新建一个文件
// using 的新用法 括号当中包裹的声明的对象 会在 大括号语句块结束后 自动释放掉 
// 当语句块结束 会自动帮助我们调用 对象的 Dispose这个方法 让其进行销毁
// using一般都是配合 内存占用比较大 或者 有读写操作时  进行使用的 
using (StreamWriter stream = new StreamWriter(path)) {// 第三步:进行xml文件序列化XmlSerializer s = new XmlSerializer(typeof(Lesson1Test));// 这句代码的含义 就是通过序列化对象 对我们类对象进行翻译 将其翻译成我们的xml文件 写入到对应的文件中// 第一个参数:文件流对象// 第二个参数:想要备翻译 的对象// 注意:翻译机器的类型 一定要和传入的对象是一致的 不然会报错s.Serialize(stream, lt);
}

3.运行测试

运行后可以看到如下的文件内容(在 path 文件夹中查看)

可以发现,只能保存 public 类型的数据

<?xml version="1.0" encoding="utf-8"?>
<Lesson1Test xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><testPublic>10</testPublic><testPUblicStr>123</testPUblicStr><testClass><test1>1</test1><test2>1.1</test2><test3>true</test3></testClass><arrayInt><int>5</int><int>6</int><int>7</int></arrayInt><listInt><int>1</int><int>2</int><int>3</int><int>4</int></listInt><listItem><Lesson1Test2><test1>1</test1><test2>1.1</test2><test3>true</test3></Lesson1Test2><Lesson1Test2><test1>1</test1><test2>1.1</test2><test3>true</test3></Lesson1Test2></listItem><testPro>0</testPro>
</Lesson1Test>

4.自定义节点名或设置属性

public class Lesson1Test
{[XmlElement("testPublic123123")]  // 将该变量对应的结点名字改为 "testPublic123123"public    int          testPublic    = 10;private   int          testPrivate   = 11;protected int          testProtected = 12;internal  int          testInternal  = 13;public    string       testPUblicStr = "123";public    int          testPro { get; set; }public    Lesson1Test2 testClass = new Lesson1Test2();public    int[]        arrayInt  = new int[3] { 5, 6, 7 };[XmlArray("IntList")]    // 改变数组对应的结点名字[XmlArrayItem("Int32")]  // 改变数组成员对应的结点名字public List<int> listInt = new List<int>() { 1, 2, 3, 4 };public List<Lesson1Test2> listItem = new List<Lesson1Test2>() { new Lesson1Test2(), new Lesson1Test2() };// 不支持字典// public Dictionary<int, string> testDic = new Dictionary<int, string>() { { 1, "123" } };
}public class Lesson1Test2
{[XmlAttribute("Test1")]    // 将该变量存储为XML属性,并改名为 "Test1"public int test1 = 1;[XmlAttribute]             // 将该变量存储为XML属性public float test2 = 1.1f;[XmlAttribute]          public bool test3 = true;
}
<?xml version="1.0" encoding="utf-8"?>
<Lesson1Test xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><testPublic>10</testPublic><testPUblicStr>123</testPUblicStr><testClass Test1="1" test2="1.1" test3="true" /><arrayInt><int>5</int><int>6</int><int>7</int></arrayInt><IntList><Int32>1</Int32><Int32>2</Int32><Int32>3</Int32><Int32>4</Int32></IntList><listItem><Lesson1Test2 Test1="1" test2="1.1" test3="true" /><Lesson1Test2 Test1="1" test2="1.1" test3="true" /></listItem><testPro>0</testPro>
</Lesson1Test>

​5. 总结:

  • 序列化流程
    1. 有一个想要保存的类对象
    2. 使用 XmlSerializer 序列化该对象
    3. 通过 StreamWriter 配合 using 将数据存储 写入文件
  • 注意:
    1. 只能序列化公共成员
    2. 不支持字典序列化
    3. 可以通过特性修改节点信息或者设置属性信息
    4. Stream 相关要配合 using 使用

二、XML 反序列化

(一)判断文件是否存在

using System.IO;string path = Application.persistentDataPath + "/Lesson1Test.xml";
if(File.Exists(path)) { ... }

(二)反序列化

​ 关键知识:

  1. using 和 StreamReader
  2. XmlSerializer 的 Deserialize 反序列化方法
using System.Xml.Serialization;// 读取文件
using (StreamReader reader = new StreamReader(path))
{// 产生了一个 序列化反序列化的翻译机器XmlSerializer s = new XmlSerializer(typeof(Lesson1Test));Lesson1Test lt = s.Deserialize(reader) as Lesson1Test;
}

​ 运行后调试,可以发现 List 类型的内容被重复添加,原因是变量 lt 初始化后, List 中有默认值,而反序列化时,Deserialize 方法会往 List 中用 Add 方法添加值,而不是覆盖原有的值。

​ 总结:

  1. 判断文件是否存在 File.Exists()

  2. 文件流获取 StreamReader reader = new StreamReader(path)

  3. 根据文件流 XmlSerializer 通过 Deserialize 反序列化出对象

​ 注意:List 对象如果有默认值,反序列化时不会清空,会往后面添加

三、IXmlSerializable 接口

​ C# 的 XmlSerializer 提供了可拓展内容,可以让一些不能被序列化和反序列化的特殊类能被处理
​ 让特殊类继承 IXmlSerializable 接口,实现其中的方法即可

(一)回顾序列化与反序列化

using System.IO;
using System.Xml;
using System.Xml.Serialization;public class TestLesson3 : IXmlSerializable
{public int test1;public string test2;
}TestLesson3 t = new TestLesson3();
t.test2 = "123";
string path = Application.persistentDataPath + "/TestLesson3.xml";
// 序列化
using (StreamWriter writer = new StreamWriter(path))
{// 序列化"翻译机器"XmlSerializer s = new XmlSerializer(typeof(TestLesson3));// 在序列化时  如果对象中的引用成员 为空 那么xml里面是看不到该字段的s.Serialize(writer, t);
}
// 反序列化
using (StreamReader reader = new StreamReader(path))
{// 序列化"翻译机器"XmlSerializer s = new XmlSerializer(typeof(TestLesson3));TestLesson3 t2 = s.Deserialize(reader) as TestLesson3;
}
<?xml version="1.0" encoding="utf-8"?>
<TestLesson3 xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><test1>0</test1><test2>123</test2>
</TestLesson3>

(二)继承 IXmlSerializable 接口

1.继承接口并实现接口函数

public class TestLesson3 : IXmlSerializable
{public int test1;public string test2;// 返回结构,返回 null 即可,不用过多了解public XmlSchema GetSchema(){return null;}// 反序列化时 会自动调用的方法public void ReadXml(XmlReader reader) { }// 序列化时 会自动调用的方法public void WriteXml(XmlWriter writer) { }
}

2.WriteXml

public void WriteXml(XmlWriter writer)
{// 在里面可以自定义序列化 的规则// 如果要自定义 序列化的规则 一定会用到 XmlWriter中的一些方法 来进行序列化// 1.写属性writer.WriteAttributeString("test1", this.test1.ToString());writer.WriteAttributeString("test2", this.test2);// 2.写节点writer.WriteElementString("test1", this.test1.ToString());writer.WriteElementString("test2", this.test2);// 3.写包裹节点XmlSerializer s = new XmlSerializer(typeof(int));writer.WriteStartElement("test1");  // 写 <test1>s.Serialize(writer, test1);         // 用序列化翻译机器写 test1 的内容writer.WriteEndElement();           // 写 </test1>XmlSerializer s2 = new XmlSerializer(typeof(string));writer.WriteStartElement("test2");  // 写 <test2>s.Serialize(writer, test2);         // 用序列化翻译机器写 test2 的内容writer.WriteEndElement();           // 写 </test2>
}

3.ReadXml

public void ReadXml(XmlReader reader)
{// 在里面可以自定义反序列化 的规则// 1.读属性this.test1 = int.Parse(reader["test1"]);this.test2 = reader["test2"];// 2.读节点// 方式一reader.Read();                         // 这时是读到的test1节点          <test1>reader.Read();                         // 这时是读到的test1节点包裹的内容  0this.test1 = int.Parse(reader.Value);  // 得到当前内容的值=reader.Read();                         // 这时读到的是尾部包裹节点        </test1>reader.Read();                         // 这时是读到的test2节点          <test2>reader.Read();                         // 这时是读到的test2节点包裹的内容  123this.test2 = reader.Value;// 方式二while (reader.Read()) {if (reader.NodeType == XmlNodeType.Element) {switch (reader.Name) {case "test1":reader.Read();this.test1 = int.Parse(reader.Value);break;case "test2":reader.Read();this.test2 = reader.Value;break;}}}// 3.读包裹元素节点XmlSerializer s = new XmlSerializer(typeof(int));XmlSerializer s2 = new XmlSerializer(typeof(string));reader.Read();  // 跳过根节点reader.ReadStartElement("test1");     // 读 <test1>test1 = (int)s.Deserialize(reader);   // 用反序列化翻译机器读 test1 的内容reader.ReadEndElement();              // 读 </test1>reader.ReadStartElement("test2");            // 读 <test2>test2 = s2.Deserialize(reader).ToString();   // 用反序列化翻译机器读 test2 的内容reader.ReadEndElement();                     // 读 </test2>
}

四、Dictionary 支持序列化与反序列化

  1. 我们没办法修改 C# 自带的类

  2. 那我们可以重写一个类继承 Dictionary,然后让这个类继承序列化拓展接口 IXmlSerializable

  3. 实现里面的序列化和反序列化方法即可

public class SerizlizedDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{public XmlSchema GetSchema() {return null;}// 自定义字典的 反序列化 规则public void ReadXml(XmlReader reader) {XmlSerializer keySer   = new XmlSerializer(typeof(TKey));XmlSerializer valueSer = new XmlSerializer(typeof(TValue));// 要跳过根节点reader.Read();// 判断 当前不是元素节点 结束 就进行 反序列化while (reader.NodeType != XmlNodeType.EndElement) {// 反序列化键TKey key = (TKey)keySer.Deserialize(reader);// 反序列化值TValue value = (TValue)valueSer.Deserialize(reader);// 存储到字典中this.Add(key, value);}}// 自定义 字典的 序列化 规则public void WriteXml(XmlWriter writer) {XmlSerializer keySer   = new XmlSerializer(typeof(TKey));XmlSerializer valueSer = new XmlSerializer(typeof(TValue));foreach (KeyValuePair<TKey, TValue> kv in this) {// 键值对 的序列化keySer.Serialize(writer, kv.Key);valueSer.Serialize(writer, kv.Value);}}
}

(一)序列化测试

public class TestLesson4
{public int test1;public SerizlizerDictionary<int, string> dic;
}public class Lesson4 : MonoBehaviour
{// Start is called before the first frame updatevoid Start() {TestLesson4 tl4 = new TestLesson4();tl4.dic = new SerizlizerDictionary<int, string>();tl4.dic.Add(1, "123");tl4.dic.Add(2, "234");tl4.dic.Add(3, "345");string path = Application.persistentDataPath + "/TestLesson4.xml";using (StreamWriter writer = new StreamWriter(path)) {XmlSerializer s = new XmlSerializer(typeof(TestLesson4));s.Serialize(writer, tl4);}}
}
<?xml version="1.0" encoding="utf-8"?>
<TestLesson4 xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><test1>0</test1><dic><int>1</int><string>123</string><int>2</int><string>234</string><int>3</int><string>345</string></dic>
</TestLesson4>

(二)反序列化测试

void Start() {TestLesson4 tl4 = new TestLesson4();using (StreamReader reader = new StreamReader(path)) {XmlSerializer s = new XmlSerializer(typeof(TestLesson4)); tl4 = s.Deserialize(reader) as TestLesson4;}
}

五、自定义 XML 数据管理类

using System;
using System.IO;
using System.Xml.Serialization;
using UnityEngine;public class XmlDataMgr
{// 单例模式public static XmlDataMgr Instance { get; } = new XmlDataMgr();// 防止外部实例化该管理类private XmlDataMgr() { }/// <summary>/// 保存数据到xml文件中/// </summary>/// <param name="data">数据对象</param>/// <param name="fileName">文件名</param>public void SaveData(object data, string fileName) {// 1.得到存储路径string path = Application.persistentDataPath + "/" + fileName + ".xml";// 2.存储文件using (StreamWriter writer = new StreamWriter(path)) {// 3.序列化XmlSerializer s = new XmlSerializer(data.GetType());s.Serialize(writer, data);}}/// <summary>/// 从xml文件中读取内容 /// </summary>/// <param name="type">对象类型</param>/// <param name="fileName">文件名</param>/// <returns></returns>public object LoadData(Type type, string fileName) {// 1.首先要判断文件是否存在string path = Application.persistentDataPath + "/" + fileName + ".xml";if (!File.Exists(path)) {path = Application.streamingAssetsPath + "/" + fileName + ".xml";if (!File.Exists(path)) {// 如果根本不存在文件 两个路径都找过了// 那么直接new 一个对象 返回给外部 无非 里面都是默认值return Activator.CreateInstance(type);}}// 2.存在就读取using (StreamReader reader = new StreamReader(path)) {// 3.反序列化 取出数据XmlSerializer s = new XmlSerializer(type);return s.Deserialize(reader);}}
}if (!File.Exists(path)) {path = Application.streamingAssetsPath + "/" + fileName + ".xml";if (!File.Exists(path)) {// 如果根本不存在文件 两个路径都找过了// 那么直接new 一个对象 返回给外部 无非 里面都是默认值return Activator.CreateInstance(type);}}// 2.存在就读取using (StreamReader reader = new StreamReader(path)) {// 3.反序列化 取出数据XmlSerializer s = new XmlSerializer(type);return s.Deserialize(reader);}}
}

http://www.mrgr.cn/p/18111732

相关文章

java+springboot+mysql疫情物资管理系统

项目介绍&#xff1a; 使用javaspringbootmysql开发的疫情物资管理系统&#xff0c;系统包含超级管理员&#xff0c;系统管理员、员工角色&#xff0c;功能如下&#xff1a; 超级管理员&#xff1a;管理员管理&#xff1b;部门管理&#xff1b;职位管理&#xff1b;员工管理&…

zore-shot,迁移学习和多模态学习

1.zore-shot 定义&#xff1a;在ZSL中&#xff0c;某一类别在训练样本中未出现&#xff0c;但是我们知道这个类别的特征&#xff0c;然后通过语料知识库&#xff0c;便可以将这个类别识别出来。概括来说&#xff0c;就是已知描述&#xff0c;对未知类别&#xff08;未在训练集中…

Python 教程之标准库概览

概要 Python 标准库非常庞大&#xff0c;所提供的组件涉及范围十分广泛&#xff0c;使用标准库我们可以让您轻松地完成各种任务。 以下是一些 Python3 标准库中的模块&#xff1a; 「os 模块」 os 模块提供了许多与操作系统交互的函数&#xff0c;例如创建、移动和删除文件和…

Debeizum 增量快照

在Debeizum1.6版本发布之后&#xff0c;成功推出了Incremental Snapshot&#xff08;增量快照&#xff09;的功能&#xff0c;同时取代了原有的实验性的Parallel Snapshot&#xff08;并行快照&#xff09;。在本篇博客中&#xff0c;我将介绍全新快照方式的原理&#xff0c;以…

系统架构设计师-软件架构设计(5)

目录 一、构件与中间件技术 1、软件复用 2、构件与中间件技术的概念 3、构件的复用 3.1 检索与提取构件 3.2 理解与评价构件 3.3 修改构件 3.4 组装构件 4、中间件 4.1 采用中间件技术的优点&#xff1a; 4.2 中间件的分类&#xff1a; 5、构件标准 5.1 CORBA&#xff08;公共…

day43-Feedback Ui Design(反馈ui设计)

50 天学习 50 个项目 - HTMLCSS and JavaScript day43-Feedback Ui Design&#xff08;反馈ui设计&#xff09; 效果 index.html <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8" /><meta name"viewport&q…

CPU密集型和IO密集型任务的权衡:如何找到最佳平衡点

关于作者&#xff1a;CSDN内容合伙人、技术专家&#xff0c; 从零开始做日活千万级APP。 专注于分享各领域原创系列文章 &#xff0c;擅长java后端、移动开发、人工智能等&#xff0c;希望大家多多支持。 目录 一、导读二、概览三、CPU密集型与IO密集型3.1、CPU密集型3.2、I/O密…

【已解决】windows7添加打印机报错:加载Tcp Mib库时的错误,无法加载标准TCP/IP端口的向导页

windows7 添加打印机的时候&#xff0c;输入完打印机的IP地址后&#xff0c;点击下一步&#xff0c;报错&#xff1a; 加载Tcp Mib库时的错误&#xff0c;无法加载标准TCP/IP端口的向导页 解决办法&#xff1a; 复制以下的代码到新建文本文档.txt中&#xff0c;然后修改文本文…

搭建测试平台开发(一):Django基本配置与项目创建

一、安装Django最新版本 1 pip install django 二、创建Django项目 首先进入要存放项目的目录&#xff0c;再执行创建项目的命令 1 django-admin startproject testplatform 三、Django项目目录详解 1 testplatform 2 ├── testplatform  # 项目的容器 3 │ ├──…

清洁机器人规划控制方案

清洁机器人规划控制方案 作者联系方式Forrest709335543qq.com 文章目录 清洁机器人规划控制方案方案简介方案设计模块链路坐标变换算法框架 功能设计定点自主导航固定路线清洁区域覆盖清洁贴边沿墙清洁自主返航回充 仿真测试仿真测试准备定点自主导航测试固定路线清洁测试区域…

ER系列路由器多网段划分设置指南

ER系列路由器多网段划分设置指南 - TP-LINK 服务支持 TP-LINK ER系列路由器支持划分多网段&#xff0c;可以针对不同的LAN接口划分网段&#xff0c;即每一个或多个LAN接口对应一个网段&#xff1b;也可以通过一个LAN接口与支持划分802.1Q VLAN的交换机进行对接&#xff0c;实现…

微信小程序导入微信地址

获取用户收货地址。调起用户编辑收货地址原生界面&#xff0c;并在编辑完成后返回用户选择的地址。 1&#xff1a;原生微信小程序接口使用API&#xff1a;wx.chooseAddress(OBJECT) wx.chooseAddress({success (res) {console.log(res.userName)console.log(res.postalCode)c…

Day02-作业(JavaScriptVue)

作业1&#xff1a;实现5秒之后&#xff0c;当前页面直接跳转到官网首页&#xff08;首页地址&#xff1a;https://www.itcast.cn&#xff09; 提示&#xff1a; 5秒之后&#xff0c;才触发某一个动作 素材&#xff1a; <!DOCTYPE html> <html lang"en"&…

【AGI】Copilot AI编程辅助工具安装教程

1. 基础激活教程 GitHub和OpenAI联合为程序员们送上了编程神器——GitHub Copilot。 但是&#xff0c;Copilot目前不提供公开使用&#xff0c;需要注册账号通过审核&#xff0c;我也提交了申请&#xff1a;这里第一期记录下&#xff0c;开启教程&#xff0c;欢迎大佬们来讨论…

【Linux】更换jdk版本

目录 一、前言二、查看jdk版本号1、项目中的版本号&#xff08;pom.xml&#xff09;2、服务器中的版本号 三、更换jdk版本1、创建java文件夹2、下载并解压JDK安装包①、下载jdk安装包②、移动到创建好的/usr/local/java路径下③、解压jdk安装包 四、删除原来的jdk版本1、删除原…

删除 iptables 中的规则

查看规则编号 要删除 iptables 中的规则&#xff0c;可以使用以下命令&#xff1a; 查看 iptables 中的规则&#xff0c;找到要删除的规则的编号&#xff1a; iptables -L --line-numbers删除指定编号的规则&#xff1a; iptables -D [chain] [rule-number]其中&#xff0c;…

设计模式再探——代理模式

目录 一、背景介绍二、思路&方案三、过程1.代理模式简介2.代理模式的类图3.代理模式代码4.代理模式还可以优化的地方5.代理模式的项目实战&#xff0c;优化后(只加了泛型方式&#xff0c;使用CGLIB的代理) 四、总结五、升华 一、背景介绍 最近在做产品过程中对于日志的统一…

c# 此程序集中已使用了资源标识符

严重性 代码 说明 项目 文件 行 禁止显示状态 错误 CS1508 此程序集中已使用了资源标识符“BMap.NET.WindowsForm.BMapControl.resources” BMap.NET.WindowsForm D:\MySource\Decompile\BMap.NET.WindowsForm\CSC 1 活动 运行程序时&a…

网络安全(黑客)自学笔记

1.网络安全是什么 网络安全可以基于攻击和防御视角来分类&#xff0c;我们经常听到的 “红队”、“渗透测试” 等就是研究攻击技术&#xff0c;而“蓝队”、“安全运营”、“安全运维”则研究防御技术。 2.网络安全市场 一是市场需求量高&#xff1b; 二则是发展相对成熟入门…

【iOS】—— UIKit相关问题

文章目录 UIKit常用的UIKit组件懒加载的优势 CALayer和UIView区别关系 UITableViewUITableView遵循的两个delegate以及必须实现的方法上述四个必须实现方法执行顺序其他方法的执行顺序&#xff1a; UICollectionView和UITableView的区别UICollectionViewFlowLayout和UICollecti…