Unity 代码操作XML文件

来源:互联网 发布:阿里云ecs ddos 编辑:程序博客网 时间:2024/05/16 15:49

第一个方法是,在什么都没有的情况下创建一个XML文件,,
第二个方法是,在上面创建好的根目录下,新建一段内容,,当然你还可以修改原来的属性或者删除,都是由对应的方法的,,
详情:修改删除方法


实现代码:

using UnityEngine;using System.Xml;   //注意引用命名空间public class createXml : MonoBehaviour {    public string path;  //路径名    // Use this for initialization    void Start () {        path = Application.dataPath + "/czhenya.xml";    }    private void OnGUI()    {        //new Rect(按钮的位置,按钮的大小)        if (GUI.Button(new Rect(0, 0, 100, 40),"CreateXML"))        {            //点击OnGUI生成按钮,创建自己的XML文件            Create();         }        if (GUI.Button(new Rect(0, 50, 100, 40), "CreateXML"))        {            //点击OnGUI生成按钮,创建自己的XML文件            Addxml();        }    }    /// <summary>    /// 生成XML文件的方法    /// </summary>    private void Create()    {        XmlDocument doc = new XmlDocument();        XmlElement root =  doc.CreateElement("root");          //创建根节点        XmlElement book = doc.CreateElement("book");           //创建子节点        XmlElement title = doc.CreateElement("title");        XmlElement author = doc.CreateElement("autor");        XmlElement year = doc.CreateElement("year");        XmlElement price = doc.CreateElement("price");        //设置节点之间的关系        book.AppendChild(title);   //为book设置自己的子节点        book.AppendChild(author);        book.AppendChild(year);        book.AppendChild(price);        root.AppendChild(book);     //为book,设置符节点(根节点)        doc.AppendChild(root);      //把根节点(root)添加到XML文件中        //为创建来的各个节点添加文本        book.SetAttribute("categroy", "悬疑");        title.InnerText = "盗墓笔记";        author.InnerText = "南派三叔";        year.InnerText = "2007";        price.InnerText = "199.99";        //一定记得保存        doc.Save(path);    }    /// <summary>    /// 添加文本    /// </summary>    private void Addxml()    {        XmlDocument doc = new XmlDocument();        doc.Load(path);  //加载  ,添加在原来的根目录下,,        XmlElement root = doc.SelectSingleNode("root") as XmlElement;  //选择根节点        XmlElement book = doc.CreateElement("book");         //新建节点        XmlElement title = doc.CreateElement("title");        XmlElement author = doc.CreateElement("autor");        XmlElement year = doc.CreateElement("year");        XmlElement price = doc.CreateElement("price");        //设置节点之间的关系        book.AppendChild(title);   //为book设置自己的子节点        book.AppendChild(author);        book.AppendChild(year);        book.AppendChild(price);        root.AppendChild(book);     //为book,设置符节点(根节点)        doc.AppendChild(root);      //把根节点(root)添加到XML文件中        //为创建来的各个节点添加文本        book.SetAttribute("categroy", "历史");        title.InnerText = "三国演义";        author.InnerText = "罗贯中";        year.InnerText = "1366";        price.InnerText = "999.99";        doc.Save(path);    } }

效果图:
效果图

原创粉丝点击