Unity 读写xml 创建 读取

在项目中遇到  需要将一些信息根据玩家走向 存储到数据 并展示出来

玩家死亡信息(死亡地区 死亡者 死亡原因 武力值)  包含多个信息

 并且需要显示玩家的死亡记录 我这里选择了xml的读写方法

//主要包含三部分功能  创建xml 添加xml 读取xml

话不多说 上代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
using System.IO;
//一定要引用命名空间
public class XmlTool : MonoBehaviour {

//创建xml 名单id 死亡地区land 死亡者name 死亡原因whydead 武力值froce
void CreateXML(string id,string land,string name, string whydead, string froce)
{
string path = Application.streamingAssetsPath + "/Tomb.xml";
Debug.Log(path);
if (!File.Exists(path))
{
//创建
XmlDocument xml = new XmlDocument();
//创建最上一层的节点。
XmlElement root = xml.CreateElement("死亡名单");
//创建子节点
XmlElement element = xml.CreateElement("名单"+id);
//设置节点的属性
element.SetAttribute("land", land);
element.SetAttribute("name", name);
element.SetAttribute("whydead", whydead);
element.SetAttribute("froce", froce);
//把节点一层一层的添加至xml中,注意他们之间的先后顺序,这是生成XML文件的顺序
root.AppendChild(element);
xml.AppendChild(root);
//最后保存文件
xml.Save(path);
}
}

//加载
void LoadXml()
{
//创建xml文档
XmlDocument xml = new XmlDocument();
xml.Load(Application.streamingAssetsPath + "/Tomb.xml");
//得到objects节点下的所有子节点
XmlNodeList xmlNodeList = xml.SelectSingleNode("死亡名单").ChildNodes;
Debug.Log("名单数量:"+ xmlNodeList.Count);
//遍历所有子节点
foreach (XmlElement xl1 in xmlNodeList)
{
Debug.Log("死亡地区:"+ xl1.GetAttribute("land");
Debug.Log("死亡者:"+ xl1.GetAttribute("name");
Debug.Log("死亡原因:"+ xl1.GetAttribute("whydead");
Debug.Log("武力值:"+ xl1.GetAttribute("froce");
}
print(xml.OuterXml);
}

//添加XML  名单id 死亡地区land 死亡者name 死亡原因whydead 武力值froce
void addXMLData(string id, string land, string name, string whydead, string froce)
{
string path = Application.streamingAssetsPath + "/Tomb.xml";
if (File.Exists(path))
{
XmlDocument xml = new XmlDocument();
xml.Load(path);
XmlNode root = xml.SelectSingleNode("死亡名单");
//下面的东西就跟上面创建xml元素是一样的。我们把他复制过来就行了
XmlElement element = xml.CreateElement("名单" + id);
//设置节点的属性
element.SetAttribute("land", land);
element.SetAttribute("name", name);
element.SetAttribute("whydead", whydead);
element.SetAttribute("froce", froce);
root.AppendChild(element);
xml.AppendChild(root);
//最后保存文件
xml.Save(path);
}
else
{
//没有文件 就创建添加
CreateXML( id,  land,  name,  whydead,  froce);
}
}

}



猜你喜欢

转载自blog.csdn.net/m0_37583098/article/details/80259997