uinty中对Xml文件的操作
最近学习unity感觉到了瓶颈,然后就回顾一下学到的知识,将它们整理下来;
unity中用户的登录与注册需要将用户名和密码保存起来的,方法有很多,如将其保存到数据库,或用JSON保存到磁盘,这里就简单说说用Xml对其进行读写操作吧;
首先,对Xml进行操作需要的命名空间是 using system.IO;
using system.Xml;
先附上一段代码,再添加注释解释吧;
usingsystem.IO;usingsystem.Xml;voidStart(){privatestringpath_Xml=Application.dataPath+"/User.xml";//保存文件的路径;if(!File.Exists(path_Xml))//判断文件是否存在,如果不存在就创建Xml文件;{XmlDocumentxmlDoc=newXmlDocument();XmlElementroot=xmlDoc.CreateElement("Root");//创建根结点;XmlDoc.AppendChild(root);//将根节点绑定到Xml对象上;XmlElementuser=xmlDoc.CreateElement("User");//再创建一个user结点;user.SetAttribute("user_name","userOne");//将userOne保存到user结点中;user.SetAttribute("user_pass","1242434");user.setAttribute("user_address","hainan");root.AppendChild(user);//将user结点绑定到root根节点上;xmlDoc.Save(path_Xml);//用Save方法将信息保存到User.xml中;}}以上就是对xml文件的写操作,那么如何进行读取呢?同样还是先创建XmlDocument对象;XmlDocumentxmlDoc=newXmlDocument()xmlDoc.Load(path_Xml);//加载文件;XmlNodeListnodeList=xmlDoc.SelectSingleNode("Root").ChildNodes;//取得Root结点下的所有子节点;foreach(XmlElementxeinnodeList){if(xe.GetAttribute("user_name")=="")//用XmlElement对象的GetAttribute方法取得结点;{}}总结:主要就是XmlDocument对象的CreateElement(),AppendChild(),Save(),Load(),SelectSingleNode()方法以及XmlElement对象的AppendChild(),SetAttribute(),GetAttribute()等方法;
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。