一、创建XML文件
1 /// <summary> 2 /// 创建XML 3 /// </summary> 4 public void CreatXML() 5 { 6 string filePath = Application.dataPath + "/my.xml";//存放路径,Assets下 7 //判断文件是否存在 8 if (!File.Exists(filePath)) 9 { 10 XmlDocument doc = new XmlDocument();//创建XML解析工厂 11 XmlElement root = doc.CreateElement("Infomation");//创建根节点 12 XmlElement child = doc.CreateElement("zhangshuai");//创建子节点 13 child.SetAttribute("id","1");//设置节点的属性 14 child.SetAttribute("name","zs"); 15 //创建下层节点 16 XmlElement child_1 = doc.CreateElement("name"); 17 //设置节点内容 18 child_1.InnerText="aa"; 19 XmlElement child_2 = doc.CreateElement("age"); 20 child_2.InnerText = "23"; 21 //将节点一层一层添加到解析工厂里面 22 child.AppendChild(child_1); 23 child.AppendChild(child_2); 24 root.AppendChild(child); 25 doc.AppendChild(root); 26 //保存文件 27 doc.Save(filePath); 28 } 29 }
二、更新XML文件
1 /// <summary> 2 /// 更新XML 3 /// </summary> 4 public void UpdateXML() 5 { 6 string filePath = Application.dataPath + "/my.xml"; 7 if (File.Exists(filePath)) 8 { 9 XmlDocument doc = new XmlDocument(); 10 doc.Load(filePath);//根据路径读取文件 11 XmlNodeList child = doc.SelectSingleNode("Infomation").ChildNodes;//得到子节点 12 foreach (XmlElement cc in child)//遍历子节点 13 { 14 if (cc.GetAttribute("id") == "1")//子节点中属性值id=1 15 { 16 cc.SetAttribute("id", "2");//更改属性值id=2 17 foreach (XmlElement cc1 in cc.ChildNodes)//继续遍历下层节点 18 { 19 if (cc1.Name == "name")//如果节点名字为"name" 20 { 21 cc1.InnerText = "ssss";//更改名字为"name"的值 22 } 23 } 24 } 25 } 26 doc.Save(filePath);//保存文件 27 } 28 29 }
三、添加
向XML文件中添加数据,和创建XML基本上方法一样。
浙公网安备 33010602011771号