Unity创建并保存XML
发布时间:2020-12-15 23:00:44 所属栏目:百科 来源:网络整理
导读:using UnityEngine;using System.Collections;using System.IO;using System.Xml;public class XMLTest : MonoBehaviour{ void Start() { XmlDocument xml = CreateXML(); AddNodeToXML(xml,"123","this is a xml test !请输入相关信息内容"); AddNodeToXML(
using UnityEngine; using System.Collections; using System.IO; using System.Xml; public class XMLTest : MonoBehaviour { void Start() { XmlDocument xml = CreateXML(); AddNodeToXML(xml,"123","this is a xml test !请输入相关信息内容"); AddNodeToXML(xml,"456","this is a xml test !请输入相关信息内容"); UpdateNodeToXML(); SaveXML(xml); } XmlDocument CreateXML() { //新建xml对象 XmlDocument xml = new XmlDocument(); //加入声明 xml.AppendChild(xml.CreateXmlDeclaration("1.0","UTF-8",null)); //加入根元素 xml.AppendChild(xml.CreateElement("Root")); return xml; } void AddNodeToXML(XmlDocument xml,string titleValue,string infoValue) { //获取根节点 XmlNode root = xml.SelectSingleNode("Root"); //添加元素 XmlElement element = xml.CreateElement("Node"); element.SetAttribute("Type","string"); //在Node节点下添加子节点 XmlElement titleElelment = xml.CreateElement("Title"); //titleElelment.SetAttribute("Title",TitleValue); titleElelment.InnerText = titleValue; XmlElement infoElement = xml.CreateElement("Info"); //infoElement.SetAttribute("Info",infoValue); infoElement.InnerText = infoValue; element.AppendChild(titleElelment); element.AppendChild(infoElement); root.AppendChild(element); } void UpdateNodeToXML() { string filepath = Application.dataPath + @"/INFO.XML"; if (File.Exists(filepath)) { XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(filepath); //根据指定路径加载xml XmlNodeList nodeList = xmldoc.SelectSingleNode("Root").ChildNodes; //Node节点 //遍历所有子节点 foreach (XmlElement xe in nodeList) { //拿到节点中属性Type=“string”的节点 if (xe.GetAttribute("Type") == "string") { //更新节点属性 xe.SetAttribute("type","text"); //继续遍历 foreach (XmlElement xelement in xe.ChildNodes) { if (xelement.Name == "TitleNode") { //修改节点名称对应的数值,而上面的拿到节点连带的属性 //xelement.SetAttribute("Title","企业简介"); xelement.InnerText = "企业简介"; } } break; } } xmldoc.Save(filepath); print("Update XML OK!"); } } void SaveXML(XmlDocument xml) { //存储xml文件 #if UNITY_EDITOR || UNITY_STANDALONE xml.Save(Application.dataPath + "/StreamingAssets/INFO.XML"); #elif UNITY_ANDROID xml.Save(Application.persistentDataPath + "/INFO.xml"); #endif } }在场景中将此脚本挂在Camera上,运行后刷新即可在StreamingAssets文件夹(如果工程无此文件夹需新建)看到INFO.xml。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |