public class L2 : MonoBehaviour
{// Start is called before the first frame updatevoid Start(){//决定存储的文件夹//存储xml文件一定要存储在各平台都可读可写可找到的路径中//1.Resources 可读不可写,打包后找不到,所以不能存储//2.Application.StreamingAssetsPath 可读,可以找到,但只有PC可写,所以不能存储//3.Application.dataPah 打包后找不到,所以不能存储//4.Application.persistentDataPath 可读可写找得到,所以存储在这里//确定存储路径string path = Application.persistentDataPath + "/PlayerInfo.xml";print(Application.persistentDataPath);//存储xml文件//XmlDocument用于创建节点存储文件//XmlDeclaration用于添加版本信息和编码//XmlElement节点类//存储有5步//1.创建文本对象XmlDocument xml = new XmlDocument();//2.添加固定信息//创建完固定信息XmlDeclaration xmlDec = xml.CreateXmlDeclaration("1.0", "UTF-8", "");//创建完固定信息之后,要把固定信息加入xml文本xml.AppendChild(xmlDec);//3.添加根节点//创建根节点XmlElement root = xml.CreateElement("Root");//创建完根节点后,把根节点加入xml文本xml.AppendChild(root);//4.为根节点添加子节点//创建子节点XmlElement name = xml.CreateElement("Name");//给子节点添加信息name.InnerText = "robot";//创建完子节点后,把子节点加到根节点下root.AppendChild(name);XmlElement atk = xml.CreateElement("atk");atk.InnerText = "10";root.AppendChild(atk);XmlElement ListInt = xml.CreateElement("ListInt");for (int i = 1; i <= 3; i++){XmlElement intNode = xml.CreateElement("Int");intNode.InnerText = i.ToString();ListInt.AppendChild(intNode);}root.AppendChild(ListInt);XmlElement itemList = xml.CreateElement("itemList");XmlElement item = xml.CreateElement("Item");//为子节点添加属性item.SetAttribute("id",1.ToString());item.SetAttribute("num", 1.ToString());itemList.AppendChild(item);root.AppendChild(itemList);//5.保存xml.Save(path);//修改xml文件//1.先判断文件是否存在if(File.Exists(path)){//2.加载后直接修改即可XmlDocument newXml = new XmlDocument();newXml.Load(path);//移除节点//寻找子节点的两种方法//1.XmlNode node = newXml.SelectSingleNode("Root").SelectSingleNode("atk");//2.//node = newXml.SelectSingleNode("Root/atk");XmlNode root2 = newXml.SelectSingleNode("Root");//移除子节点的方法root2.RemoveChild(node);XmlElement hp = newXml.CreateElement("hp");hp.InnerText = "100";root2.AppendChild(hp);//修改完之后进行保存newXml.Save(path);}}
}