Unity3D使用C#创建、解析XML与添加、更改节点(及其注意事项)
发布日期:2021-05-10 09:22:21 浏览次数:26 分类:精选文章

本文共 20343 字,大约阅读时间需要 67 分钟。

一、使用C#创建如下的XML

二、创建该XML的步骤
①创建该XML的数据类
using System.Collections;using System.Collections.Generic;using UnityEngine;public class SingleAccountLogonXmlInfo{    //账号的Id    public int UserId { get; set; }    //账号的用户名    public string UserName { get; set; }    //账号的密码    public string UserPassword { get; set; }    //账号的权限    public string UserAuthority { get; set; }    //账号的联系电话    public string UserTelNumber { get; set; }    //账号的前一次登录时间    public string UserPreviousLogonTime { get; set; }    //账号的当前登录时间    public string UserCurrentLogonTime { get; set; }}

②创建xml生成(生成的位置为Assets-->StreamingAssets文件夹下(如果没有StreamingAssets文件夹请创建一个)、节点添加、修改脚本
using System.Collections;using System.Collections.Generic;using UnityEngine;using System.IO;using System.Xml;using System;namespace Control{	public class Ctrl_CreatLogonXML : MonoBehaviour	{        public static Ctrl_CreatLogonXML Instance;                              //本脚本实例        private void Awake()        {            Instance = this;        }        void Start()		{           BaseXmlFile("Account.xml", "Account", 1, "admin", "admin", "", "", "", "");        }              ///         /// 创建XML文件        ///         /// 
public XmlDocument CreateXML() { //新建xml对象 XmlDocument xml = new XmlDocument(); //加入声明 xml.AppendChild(xml.CreateXmlDeclaration("1.0", "UTF-8", null)); return xml; } /// /// 添加节点到XML中 /// /// XmlDocument /// 根节点名称 /// 用户ID值 /// 用户名 /// 用户密码 /// 用户权限 /// 用户的电话号码 /// 上一次登录时间 /// 当前登录时间 public void AddNodeToXML(XmlDocument xml,string xmlFileName, string RootNodeName, int userId,string userName,string userPassword,string userAuthority,string userTelNumber,string userPreviousLogonTime,string userCurrentLogonTime) { string filepath = Application.dataPath + "/StreamingAssets/" + xmlFileName; if (File.Exists(filepath)) { xml.Load(filepath); //根据指定路径加载xml print("xml的文件路径=" + filepath); XmlNode rootNode = xml.SelectSingleNode(RootNodeName); //根节点 print("得到的根节点="+rootNode); //添加子节点 XmlElement element = xml.CreateElement("User"); //添加子节点的属性 element.SetAttribute("userId", userId.ToString()); element.SetAttribute("userName", userName); element.SetAttribute("userPassword", userPassword); element.SetAttribute("userAuthority", userAuthority); element.SetAttribute("userTelNumber", userTelNumber); element.SetAttribute("userPreviousLogonTime", userPreviousLogonTime); element.SetAttribute("userCurrentLogonTime", userCurrentLogonTime); rootNode.AppendChild(element); xml.Save(filepath); } else { BaseXmlFile("Account.xml","Account", 1, "admin", "admin", "Ower", "", "", ""); } } /// /// 创建xml基础文件 /// /// XmlDocument /// 根节点名称 /// 用户ID值 /// 用户名 /// 用户密码 /// 用户权限 /// 用户的电话号码 /// 上一次登录时间 /// 当前登录时间 public void BaseXmlFile(string xmlFileName, string RootNodeName, int userId, string userName, string userPassword, string userAuthority, string userTelNumber, string userPreviousLogonTime, string userCurrentLogonTime) { XmlDocument xml = CreateXML(); string filepath = Application.dataPath + "/StreamingAssets/" + xmlFileName; if (!File.Exists(filepath)) { //加入根节点 xml.AppendChild(xml.CreateElement(RootNodeName)); //获取根节点 XmlNode root = xml.SelectSingleNode(RootNodeName); //添加子节点 XmlElement element = xml.CreateElement("User"); //添加子节点的属性 element.SetAttribute("userId", userId.ToString()); element.SetAttribute("userName", userName); element.SetAttribute("userPassword", userPassword); element.SetAttribute("userAuthority", userAuthority); element.SetAttribute("userTelNumber", userTelNumber); element.SetAttribute("userPreviousLogonTime", userPreviousLogonTime); element.SetAttribute("userCurrentLogonTime", userCurrentLogonTime); root.AppendChild(element); SaveXML(xml, xmlFileName); } } /// /// 更新节点内容到XML文件中 /// /// XML文件名称 /// 根节点名称 /// 用户Id值 /// 用户名 /// 用户密码 /// 用户权限 /// 用户的电话号码 /// 上一次登录时间 /// 下一次登录时间 public void UpdateNodeContentToXML(string xmlFileName,string RootNodeName, int userId, string userName, string userPassword, string userAuthority, string userTelNumber, string userPreviousLogonTime, string userCurrentLogonTime) { string filepath = Application.dataPath + "/StreamingAssets/" + xmlFileName; if (File.Exists(filepath)) { XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(filepath); //根据指定路径加载xml print("xml的文件路径=" + filepath); XmlNodeList nodeList = xmldoc.SelectSingleNode(RootNodeName).ChildNodes; //根节点下的所有子节点 //遍历所有子节点 for (int i = 0; i < nodeList.Count; i++) { //根据ID 或用户名判断进行信息修改,如果这两项项中的任何一项符合就可以更改对应的内容 if (nodeList[i].Attributes[0].InnerText == userId.ToString().Trim()|| nodeList[i].Attributes[1].InnerText == userName.Trim()) { //nodeList[i].Attributes[0].InnerText = userId.ToString(); //nodeList[i].Attributes[1].InnerText = userName; if (userPassword.Trim()!=null&& userAuthority.Trim()!=null&& userTelNumber.Trim()!=null) { nodeList[i].Attributes[2].InnerText = userPassword.Trim(); nodeList[i].Attributes[3].InnerText = userAuthority.Trim(); nodeList[i].Attributes[4].InnerText = userTelNumber.Trim(); if (userPreviousLogonTime==null&& userCurrentLogonTime==null) { DateTime NowTime = DateTime.Now.ToLocalTime(); nodeList[i].Attributes[5].InnerText = NowTime.ToString("yyyy-MM-dd HH:mm:ss"); nodeList[i].Attributes[6].InnerText = NowTime.ToString("yyyy-MM-dd HH:mm:ss"); } else { nodeList[i].Attributes[5].InnerText = userPreviousLogonTime.ToString(); nodeList[i].Attributes[6].InnerText = userCurrentLogonTime.ToString(); } } } } xmldoc.Save(filepath); print("节点属性内容更新成功"); } else { Debug.LogWarning(GetType()+ "/UpdateNodeContentToXML()/你所查询的路径不存在,请检查!"); } } /// /// 保存XML文件 /// /// XmlDocument /// xml的文件名称 public void SaveXML(XmlDocument xml,string xmlFileName) { xml.Save(Application.dataPath + "/StreamingAssets/" + xmlFileName); } }//class_end}

③创建解析该XML内容的脚本
using System.Collections;using System.Collections.Generic;using UnityEngine;using System;using System.IO;using System.Xml;namespace Control{	public class Ctrl_AnalysisLogonXMLInfo : MonoBehaviour	{        public static Ctrl_AnalysisLogonXMLInfo Instance;                               //本脚本实例        private List
_SingleAccountInfoList; //存储账号登录信息的列表 private SingleAccountLogonXmlInfo _SingleAccountInfo; //登录xml信息的每一条数据 //private string _LogonXmlInfoPath = "LogonXML/LogonXML.xml"; //账号信息的xml路径 private void Awake() { Instance = this; } void Start() { // GetLogonXMLInfo(_LogonXmlInfoPath,"Account"); } ///
/// 获取到所有的账号信息 /// ///
public List
GetAllAccountInfo() { return _SingleAccountInfoList; } ///
/// 获取到所有账号的数目 /// ///
public int GetAllAccountNumbers() { int accountNum = 0; accountNum = _SingleAccountInfoList.Count; return accountNum; } ///
/// 获取到账号登录的XML信息 /// ///
账号xml路径 ///
账号根节点名称 public void GetLogonXMLInfo(string xmlPath,string rootNodeName) { //实例化 _SingleAccountInfoList = new List
(); string path = "file://" + Application.dataPath+ "/StreamingAssets/"+xmlPath; print(path); XmlDocument doc = new XmlDocument(); doc.Load(path); //获取到根节点 XmlNode rootNode = doc.SelectSingleNode(rootNodeName); XmlNodeList childNodes = rootNode.ChildNodes; foreach (XmlNode nodeItem in childNodes) { //实例化 _SingleAccountInfo = new SingleAccountLogonXmlInfo(); _SingleAccountInfo.UserId =Convert.ToInt32(nodeItem.Attributes[0].InnerText); print("id1=" + _SingleAccountInfo.UserId); _SingleAccountInfo.UserName = nodeItem.Attributes[1].InnerText; _SingleAccountInfo.UserPassword = nodeItem.Attributes[2].InnerText; _SingleAccountInfo.UserAuthority = nodeItem.Attributes[3].InnerText; _SingleAccountInfo.UserTelNumber = nodeItem.Attributes[4].InnerText; _SingleAccountInfo.UserPreviousLogonTime = nodeItem.Attributes[5].InnerText; _SingleAccountInfo.UserCurrentLogonTime = nodeItem.Attributes[6].InnerText; _SingleAccountInfoList.Add(_SingleAccountInfo); } } }//class_end}

三、使用方法
①创建一个测试XML的创建、添加、更改子节点内容的脚本
using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.UI;using System.IO;using System.Xml;using Control;using System;namespace View{	public class CreateXMLTest : MonoBehaviour	{        public Text TxtId;        public Text TxtName;        public Text TxtPwd;        public Text TxtAuthority;        public Text TxtTelNumber;        public Text TxtPreviousLogonTime;        public Text TxtCurrentLogonTime;        public InputField UserId;        public InputField UserName;        public InputField UserPwd;        public InputField UserAuthority;        public InputField UserTelNumber;        public InputField UserPreviousLogonTime;        public InputField UserCurrentLogonTime;        List
_AllAccountInfo; private string _LogonXmlInfoPath = "Account.xml"; //账号信息的xml路径 //创建XML IEnumerator Start() { yield return new WaitForSeconds(2F); Ctrl_AnalysisLogonXMLInfo.Instance.GetLogonXMLInfo(_LogonXmlInfoPath, "Account"); } //更新XML内容 private void Update() { if (Input.GetKeyDown(KeyCode.A)) { Ctrl_CreatLogonXML.Instance.UpdateNodeContentToXML("Account.xml", "Account", 2, "我是更新的用户名", "我是更新的密码", "我是更新的权限", "我是更新的电话号码", null, null); //实例化 _AllAccountInfo = new List
(); //获取账号信息 _AllAccountInfo = Ctrl_AnalysisLogonXMLInfo.Instance.GetAllAccountInfo(); print(_AllAccountInfo.Count); foreach ( var s in _AllAccountInfo) { print(s.UserId); } } } //用户注册 public void BtnRegister() { if (UserName.text.Trim()!=null&&UserPwd.text.Trim()!=null&&UserTelNumber.text.Trim()!=null||UserAuthority.text.Trim()!=null) { //查询XML的数据 int accountNum= Ctrl_AnalysisLogonXMLInfo.Instance.GetAllAccountNumbers(); if (accountNum>=0) { TxtId.text= (accountNum + 1).ToString(); } DateTime NowTime = DateTime.Now.ToLocalTime(); XmlDocument xml = Ctrl_CreatLogonXML.Instance.CreateXML(); print(UserName.text.Trim()); //赋值数据 Ctrl_CreatLogonXML.Instance.AddNodeToXML(xml,_LogonXmlInfoPath, "Account", accountNum + 1, UserName.text.Trim(), UserPwd.text.Trim(), UserAuthority.text.Trim(), UserTelNumber.text.Trim(), NowTime.ToString("yyyy-MM-dd HH:mm:ss"), NowTime.ToString("yyyy-MM-dd HH:mm:ss")); //Ctrl_CreatLogonXML.Instance.SaveXML(xml, "Account.xml"); TxtId.text = (accountNum + 1).ToString(); TxtName.text = UserName.text.Trim(); TxtPwd.text = UserPwd.text.Trim(); TxtAuthority.text = UserAuthority.text.Trim(); TxtTelNumber.text = UserTelNumber.text.Trim(); TxtPreviousLogonTime.text = NowTime.ToString("yyyy-MM-dd HH:mm:ss"); TxtCurrentLogonTime.text = NowTime.ToString("yyyy-MM-dd HH:mm:ss"); } }

Unity设计的测试界面如下:

一、操作如下:
①将Ctrl_CreatLogonXML、CreateXMLTest脚本都挂载到_ScriptMgr物体上
②给BtnRegister按钮添加注册方法
③运行该场景,输入内容,可以观察到在Assets-->StreamingAssets文件下多出了一个Account.xml文件,用VS打开该文件此时内容如下:

④运行场景按下大写的字母键“A”,此时该XML的内容如下:

二、操作如下:
①创建登录的控制脚本
using System.Collections;using System.Collections.Generic;using UnityEngine;namespace Control{	public class Ctrl_UserLogon:Ctrl_AnalysisLogonXMLInfo    {        private static Ctrl_UserLogon _Instance;                                    //本类实例        List
_AllAccountInfo; //用户的账号信息 private bool LogonMark = false; //登录是否成功标识 private string userName = ""; //用户名 private string userPwd = ""; //用户密码 //private string _LogonXmlInfoPath = "LogonXML/LogonXML.xml"; //账号信息的xml路径 private string _LogonXmlInfoPath = "Account.xml"; //账号信息的xml路径 ///
/// 本类实例 /// ///
public static Ctrl_UserLogon GetInstance() { if(_Instance==null) { _Instance = new Ctrl_UserLogon(); } return _Instance; } void Start() { //获取到账号登录的XML信息 Ctrl_AnalysisLogonXMLInfo.Instance.GetLogonXMLInfo(_LogonXmlInfoPath, "Account"); } ///
/// 账号登录判断 /// ///
用户名称 ///
用户密码 ///
/// true:登录成功 /// false:登录失败 ///
public bool UserLogon(string userName, string userPwd) { //实例化 _AllAccountInfo = new List
(); //获取账号信息 _AllAccountInfo=Ctrl_AnalysisLogonXMLInfo.Instance.GetAllAccountInfo(); //账号信息判断 if (!string.IsNullOrEmpty(userName) || !string.IsNullOrEmpty(userPwd)) { for (int i = 0; i < _AllAccountInfo.Count; i++) { if (_AllAccountInfo[i].UserName == userName.Trim() && _AllAccountInfo[i].UserPassword == userPwd.Trim()) { LogonMark=true; } } } else { LogonMark=false; } return LogonMark; } }//class_end}

②创建登录的视图层脚本
using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.UI;using UnityEngine.SceneManagement;using Global;using Control;namespace View{	public class View_LogonInfo : MonoBehaviour	{        public InputField userNameInput;                                                      //用户名称        public InputField userPwdInput;                                                       //用户密码		void Start()		{					}        ///         /// 登录        ///         public void BtnLogon()        {            string userName = userNameInput.text;            string userPwd = userPwdInput.text;            print("用户名="+userName);            print("密码=" + userPwd);            bool logonMark=Ctrl_UserLogon.GetInstance().UserLogon(userName,userPwd);            if (logonMark == true)            {                                print("登陆成功");                //进入下一个场景                GlobalParaMgr.NextScenesName = ScenesEnum.DaTingScenes;//大厅场景                SceneManager.LoadScene(ConvertEnumToString.GetInstance().GetStrByEnumScenes(ScenesEnum.LoadingScenes));            }            else            {                print("登陆失败");            }                    }	}//class_end}

③将这两个登录脚本都挂载给登录场景,运行输入对应的账号即可登录

注意事项:创建出来的该XML在VS环境中打开如下:

该XML在浏览器中打开如下:

如果需要将该XML在浏览器中显示效果如VS环境中的显示一样,则修改Ctrl_CreatLogonXML、Ctrl_AnalysisLogonXMLInfo脚本内容即可
element.SetAttribute("userCurrentLogonTime", userCurrentLogonTime);element.SetAttribute("userPreviousLogonTime", userPreviousLogonTime);element.SetAttribute("userTelNumber", userTelNumber);element.SetAttribute("userAuthority", userAuthority);element.SetAttribute("userPassword", userPassword);element.SetAttribute("userName", userName);element.SetAttribute("userId",userId.ToString());
//根据ID 或用户名判断进行信息修改,如果这两项项中的任何一项符合就可以更改对应的内容                    if (nodeList[i].Attributes[6].InnerText == userId.ToString().Trim()|| nodeList[i].Attributes[5].InnerText == userName.Trim())                    {                        //nodeList[i].Attributes[6].InnerText = userId.ToString();                        //nodeList[i].Attributes[5].InnerText = userName;                        if (userPassword.Trim()!=null&& userAuthority.Trim()!=null&& userTelNumber.Trim()!=null)                        {                            nodeList[i].Attributes[4].InnerText = userPassword.Trim();                            nodeList[i].Attributes[3].InnerText = userAuthority.Trim();                            nodeList[i].Attributes[2].InnerText = userTelNumber.Trim();                            if (userPreviousLogonTime==null&& userCurrentLogonTime==null)                            {                                DateTime NowTime = DateTime.Now.ToLocalTime();                                nodeList[i].Attributes[1].InnerText = NowTime.ToString("yyyy-MM-dd HH:mm:ss");                                nodeList[i].Attributes[0].InnerText = NowTime.ToString("yyyy-MM-dd HH:mm:ss");                            }                            else                            {                                nodeList[i].Attributes[1].InnerText = userPreviousLogonTime.ToString();                                nodeList[i].Attributes[0].InnerText = userCurrentLogonTime.ToString();                            }                                                    }                                           }
//实例化                _SingleAccountInfo = new SingleAccountLogonXmlInfo();                _SingleAccountInfo.UserId =Convert.ToInt32(nodeItem.Attributes[6].InnerText);                print("id1=" + _SingleAccountInfo.UserId);                _SingleAccountInfo.UserName = nodeItem.Attributes[5].InnerText;                _SingleAccountInfo.UserPassword = nodeItem.Attributes[4].InnerText;                _SingleAccountInfo.UserAuthority = nodeItem.Attributes[3].InnerText;                _SingleAccountInfo.UserTelNumber = nodeItem.Attributes[2].InnerText;                _SingleAccountInfo.UserPreviousLogonTime = nodeItem.Attributes[1].InnerText;                _SingleAccountInfo.UserCurrentLogonTime = nodeItem.Attributes[0].InnerText;                _SingleAccountInfoList.Add(_SingleAccountInfo);
上一篇:Unity3D中场景的移动控制(使用键盘控制移动,鼠标控制场景方向)
下一篇:控制Unity物体的旋转

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月22日 00时13分02秒