Unity中简单的xml使用创建方法
using UnityEngine;
using System.Collections;using System.IO;
using System.Xml;
public class CC_xml
{
public static void CreateXml(string path)//静态方法 创建 xml
{
if (File.Exists(path)==false) //判断文件是否存在
{
XmlDocument xdoc = new XmlDocument(); //声明 xml 对象
XmlDeclaration xd = xdoc.CreateXmlDeclaration("1.0","UTF-8","yes");// 声明 描述文件
xdoc.AppendChild(xd);// 把当前 声明文件 添加到 xml 对象
XmlNode rootNode = xdoc.CreateElement("root"); //创建了根节点
XmlNode stuNode = xdoc.CreateElement("student"); // 创建了子节点
XmlNode name1Node = xdoc.CreateElement("name"); // 子节点里填入 属性 及内容
XmlAttribute name1Attribute = xdoc.CreateAttribute("name");
name1Attribute.Value = "ytf";
name1Node.Attributes.Append(name1Attribute);//使用节点里的属性进行添加 属性名称
name1Node.InnerText = "1991";
XmlNode name2Node = xdoc.CreateElement("name");
XmlAttribute name2Attribute = xdoc.CreateAttribute("name");
name2Attribute.Value = "zzz";
name2Node.Attributes.Append(name2Attribute);
name2Node.InnerText = "1991";
stuNode.AppendChild(name1Node);// 树状结构的 父子关系 赋予
stuNode.AppendChild(name2Node);
rootNode.AppendChild(stuNode);
xdoc.AppendChild(rootNode);
xdoc.Save(path);// 写入到 物理地址里
}
}
public static void EditXml(string path,string node,string innnerText)// 静态的编辑方法
{
XmlDocument xdoc = new XmlDocument();// 声明xml对象
xdoc.Load(path); // 加载 xml到对象
XmlNodeList xlist = xdoc.SelectNodes(node);// 选择节点
for (int i = 0; i < xlist.Count; i++)
{
xlist[i].InnerText=innnerText;
}
xdoc.Save(path);// 存储到物理地址
}
public static string[] ReadXml(string path)
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(path);
XmlNodeList xlist = xdoc.SelectNodes("/root/student/name");
string[] aa = new string[xlist.Count];
//return xlist.Count.ToString();
for (int i = 0; i <xlist.Count; i++)
{
aa[i] = xlist[i].InnerText;
}
return aa;
}
}
简单的总结一下xml的使用