Unity学习笔记--数据持久化XML文件(1)
1.Unity学习笔记--基础2.Unity学习笔记--入门3.Unity学习笔记--数据持久化之PlayerPrefs的使用
4.Unity学习笔记--数据持久化XML文件(1)
5.Unity学习笔记--数据持久化XML文件(2)6.Unity学习笔记--数据持久化Json7.NGUI学习笔记(1)8.NGUI学习笔记29.NGUI学习笔记3.510.NGUI学习笔记4.011.Unity 热更--AssetBundle学习笔记 0.712.Unity 热更--AssetBundle学习笔记 0.813.Unity 热更--AssetBundle学习笔记 1.0【AB包资源加载工具类的实现】14.[2]自定义Lua解析方式15.Unity热更学习toLua使用--[1]toLua的导入和默认加载执行lua脚本16.自定义Lua解析器管理器-------演化脚本V0.517.使用自定义委托来调用Lua中的多返回值和长参数类型函数18.使用自定义lua解析管理器调用lua脚本中的table19.Lua热更学习--使用toLua中的协程20.toLua中Lua调用C#中的类21.热更学习笔记10~11----lua调用C#中的List和Dictionary、拓展类中的方法22.Lua中调用ref和out修饰参数的函数/重载函数23.Unity 编辑器中获取选中的文件夹、文件路径XML相关
Xml是可拓展标记语言,一种文件格式。我们使用xml来完成对数据持久化的存储。等待我们有一程序运行结束之后,将内存中的数据进行保存,(保存在硬盘/服务器)实现对数据的持久化存储。
xml文件的读取和保存以及修改
要点:
-
XMl文件的加载
-
XML文件节点的查找访问
-
XML文件节点内容的读取 (InnerText还是Attributes["id"].Value 形式访问)
代码中有详细注释!可供参考对比学习!
using System.IO; using System.Xml; using UnityEngine; namespace Building.XML { public class LoadXMLFile:MonoBehaviour { private void Start() { //得到xml文件 XmlDocument xmlFile = new XmlDocument(); //通过加载text格式进行解析成xml形式进行获取 //TextAsset textAsset = Resources.Load<TextAsset>("Text"); // xmlFile.LoadXml(textAsset.text); //通过路径进行加载 xmlFile.Load(Application.streamingAssetsPath+"/Text.xml"); //读取xml中节点 XmlNode root = xmlFile.SelectSingleNode("PlayerInfo"); XmlNode nodeName = root.SelectSingleNode("Name"); XmlNode nodeList = root.SelectSingleNode("Item"); //获取自定义版本的数据结构类型 print(nodeList.Attributes["id"].Value); print(nodeList.Attributes["size"].Value); //或者 print(nodeList.Attributes.GetNamedItem("id").Value); print(nodeList.Attributes.GetNamedItem("size").Value); //直接获取数组中的元素 XmlNode tempNodeList1 = root.SelectSingleNode("ItemList1"); XmlNodeList xmlNodeList1 = tempNodeList1.SelectNodes("Item"); //找出List中所有的节点 打印节点组中的 id size节点的InnerText //var 类型推断不出来 XmlNode类型 foreach (XmlNode item in xmlNodeList1) { print(item.Name); print(item.SelectSingleNode("id").InnerText); /* <Item> <id>2003</id>> 通过InnerText来访问<> <>中间的内容 <size>17.5</size>> </Item>>*/ print(item.SelectSingleNode("size").InnerText); } for (int i = 0; i < xmlNodeList1.Count; i++) { print(xmlNodeList1[i].Name); print(xmlNodeList1[i].SelectSingleNode("id").InnerText); print(xmlNodeList1[i].SelectSingleNode("size").InnerText); } //直接获取数组中的元素 形式 innerText访问还是获取 Attributes["size"].Value 访问数值 //-------注意区分元素中是否还有子节点 根据是否有子节点来选择获取节点内容 XmlNode tempNodeList = root.SelectSingleNode("ItemList"); XmlNodeList xmlNodeList = tempNodeList.SelectNodes("Item"); //找出List中所有的节点 打印节点组中的 id size节点的InnerText //var 类型推断不出来 XmlNode类型 foreach (XmlNode item in xmlNodeList) { print(item.Name); print(item.Attributes["id"].InnerText); print(item.Attributes["size"].Value); } for (int i = 0; i < xmlNodeList.Count; i++) { print(xmlNodeList[i].Name); print(xmlNodeList[i].Attributes["id"].Value); //<Item id="2011" size="15.5"/> //单行内嵌的 通过Attributs["name"].Value访问 print(xmlNodeList[i].Attributes["size"].Value); } //============================读================ //==================xml存储的路径 // 1.Resources 可读 不可写 打包后找不到 × // 2.Application.streamingAssetsPath 可读 PC端可写 找得到 × // 3.Application.dataPath 打包后找不到 × // 4.Application.persistentDataPath 可读可写找得到 √ string path = Application.streamingAssetsPath + "/xmlSaveFile.xml"; print(Application.persistentDataPath); //创建固定版本信息 XmlDocument saveXmlFile = new XmlDocument(); //文件格式声明 XmlDeclaration xmlDeclaration = saveXmlFile.CreateXmlDeclaration("1.0", "utf-8", ""); saveXmlFile.AppendChild(xmlDeclaration); //添加根节点 //这里以存储班级信息为例子 XmlElement classInfo =saveXmlFile.CreateElement("ClassInfo"); saveXmlFile.AppendChild(classInfo); //创建子节点 XmlElement teacher = saveXmlFile.CreateElement("teacher"); classInfo.AppendChild(teacher); XmlElement teacherName = saveXmlFile.CreateElement("teacherName"); teacherName.InnerText = "TonyChang"; teacher.AppendChild(teacherName); XmlElement teacherId = saveXmlFile.CreateElement("teacherId"); teacherId.InnerText = "3306";//设置teacherID名称 teacher.AppendChild(teacherId); //学生信息模块 XmlElement stusElement = saveXmlFile.CreateElement("Students"); XmlElement stuEle;//学生信息 for (int i = 0; i < 15; i++) { stuEle = saveXmlFile.CreateElement("Student"); stuEle.SetAttribute("stuNo", (i + 1).ToString()); stuEle.SetAttribute("age", 19.ToString()); stusElement.AppendChild(stuEle); } //学生信息模块添加到xml文件中 classInfo.AppendChild(stusElement); //保存Xml文件 saveXmlFile.Save(path); //----------------------XML的内容修改------------------------ if (File.Exists(path)) { XmlDocument Xml1 = new XmlDocument(); //加载到新建的的xml文件中 Xml1.Load(path); //获取要修改的文件节点 XmlNode changeNode; changeNode = Xml1.SelectSingleNode("ClassInfo/teacher/teacherId"); //将3306-->8888 changeNode.InnerText = "8888"; //---删除(通过父节点删除) XmlNode FatherNode = Xml1.SelectSingleNode("ClassInfo/teacher"); FatherNode.RemoveChild(changeNode); //---添加新的节点 XmlNode changedNode=Xml1.CreateElement("teacherId"); changedNode.InnerText = "8888"; FatherNode.AppendChild(changedNode); //修改了记得保存 Xml1.Save(path); } } } }
textXML文件
<?xml version="1.0" encoding="utf-8"?> <!--注释内容--> <PlayerInfo > <name>TonyChang</name> <age>18</age> <height>175.5</height>> <Item id="1997" size="12.5"/> <Item1> <id>1998</id>> <size>12.25</size> </Item1>> <ItemList1> <!--属性 和元素节点的区别? 表现形式不同的同种意义 --> <Item> <id>2002</id>> <size>16.5</size>> </Item>> <Item> <id>2003</id>> <size>17.5</size>> </Item>> <Item> <id>2004</id>> <size>18.5</size>> </Item>> </ItemList1> <ItemList> <!--属性 和元素节点的区别? 表现形式不同的同种意义 --> <Item id="2011" size="15.5"/> <Item id="2012" size="16.5"/> <Item id="2013" size="17.5"/> </ItemList> </PlayerInfo>
文件格式如图所示;
生成新建的“xmlSaveFile.xml”文件内容
XML的序列化与反序列化
序列化:
using System.Collections.Generic; using System.IO; using System.Xml.Serialization; using UnityEngine; public class Test { public int testPub = 10; private int testPri = 5; protected int testProtect = 12; internal int testInter = 15; public string testStr = "TonyChang"; //属性 public int testPro { get; set; } //数组 public int[] arrayInt=new []{2,4,6,8}; //自定义类 public Test2 Test2 = new Test2(); //list //更改数组属性名字 [XmlArray("IntList")] [XmlArrayItem("TCInt")] public List<int> listInt=new List<int>(){1,5,7,8,9}; //不支持字典 // public Dictionary<int, string> testDic = new Dictionary<int, string>() {{1, "Jerry"},{2,"Tom"}}; } public class Test2 { //属性标签 [XmlAttribute("Test2")] public int xmlTest = 5; [XmlAttribute()] public float test2Float = 6.6f; [XmlAttribute()] public bool aryUok = true; } /// <summary> /// XML的序列化与反序列化 /// </summary> public class XMLDemo : MonoBehaviour { private void Start() { //要存储为XML文件的文件流 Test test = new Test(); string path = Application.persistentDataPath + "/XMLTest01.xml"; print(path); //流语句 //using加载文件 文件加载结束之后则会自动关闭 using(StreamWriter stream = new StreamWriter(path) ) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(Test)); //将XML文件序列化 写入流中 //流根据配置的写入地址进行设置 xmlSerializer.Serialize(stream,test); } } }
- 只能进行公共类型变量的存储
- 不支持字典存储
对应生成的XML文件如下图所示:
反序列化:
//反序列化 //判断是否存在要读取的XML文件 if (File.Exists(path)) { using (StringReader reader = new StringReader(path)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(Test)); Test testReaded=xmlSerializer.Deserialize(reader) as Test; } } //tips: //list对象中有默认值时候,反序列化时候会把默认值再次添加到list数组中 //可以理解为 当前反序列化时候要考察各种变量的默认值(初始值) //如果过本身序列化时候会有new List(){1,2,3}之类的赋值操作 //则反序列化时会重新将1,2,3数值添加到list数组中,得到的 //反序列化结果中会有两个1,2,3 1,2,3 内容
本文作者:畅知
本文链接:https://www.cnblogs.com/TonyCode/p/17845010.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步