Unity中的XML文件创建,读取,修改,添加

发表于2017-09-01
评论0 4.5k浏览

Unity中用户的登录与注册需要将用户名和密码保存起来的,方法有很多,如将其保存到数据库,或用JSON保存到磁盘,这里就简单说说用Xml对其进行读写操作吧,如果有想了解unity中关于XML内容的可以看看

        

首先,对Xml进行操作需要的命名空间是

using System.Xml;
using System.IO;

一个是对XML文件的命名空间,里面有关xml的很多api 

一个是对文件读写的命名空间,是对文件的读取,保存操作。

       

先附上一段代码,再添加注释解释吧;        

       

  1. using system.IO;  
  2. using system.Xml;  
  3.   
  4. void Start()  
  5. {  
  6.     private string path_Xml=Application.dataPath "/User.xml";  //保存文件的路径;  
  7.       
  8.     if(!File.Exists(path_Xml))                               //判断文件是否存在,如果不存在就创建Xml文件;  
  9.     {  
  10.         XmlDocument xmlDoc=new XmlDocument();    
  11.         XmlElement root=xmlDoc.CreateElement("Root");       //创建根结点;  
  12.         XmlDoc.AppendChild(root);                           //将根节点绑定到Xml对象上;  
  13.         XmlElement user=xmlDoc.CreateElement("User");       //再创建一个user结点;  
  14.         user.SetAttribute("user_name","userOne");           //将userOne保存到user结点中;  
  15.         user.SetAttribute("user_pass","1242434");  
  16.         user.setAttribute("user_address","hainan");  
  17.         root.AppendChild(user);                             //将user结点绑定到root根节点上;  
  18.         xmlDoc.Save(path_Xml);                              //用Save方法将信息保存到User.xml中;  
  19.     }  
  20.       
  21. }  
  22.   
  23. 以上就是对xml文件的写操作,那么如何进行读取呢?  
  24.   
  25. 同样还是先创建XmlDocument对象;  
  26.   
  27. XmlDocument xmlDoc=new XmlDocument()  
  28. xmlDoc.Load(path_Xml);                //加载文件;  
  29. XmlNodeList nodeList=xmlDoc.SelectSingleNode("Root").ChildNodes;      //取得Root结点下的所有子节点;  
  30. foreach(XmlElement xe in nodeList)  
  31. {  
  32.     if(xe.GetAttribute("user_name")=="")                         //用XmlElement对象的GetAttribute方法取得结点;  
  33.     {  
  34.               
  35.     }  
  36. }  
  37.   
  38. 总结:主要就是XmlDocument对象的CreateElement(),AppendChild(),Save(),Load(),SelectSingleNode()方法以及  
  39.     XmlElement对象的AppendChild(),SetAttribute(),GetAttribute()等方法;  

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引