Unity3d基础学习第10天

目录

    • XML解析
      • 1.加载文件
      • 2.获取根节点
      • 3.添加子节点元素
      • 4.读取XML 遍历1
      • 5.替换 遍历2
      • 6.保存数据在文件中
    • PlayerPrefs 保存数据

XML解析

1.加载文件

    string  fileName = "/bookxml.xml";
	string path = string.Empty;
    Debug.Log (Application.dataPath);//项目中的assets目录
	path = Application.dataPath + fileName;
	XmlDocument doc = new XmlDocument ();
	doc.Load (path); 
    //加载xml文件的内容到内存中,并生成节点(元素节点,文本节点,属性节点)的树状结构
    //元素节点:标签和标签内容组成元素

2.获取根节点

    //XmlNode是XmlElement的父类
    XmlNode rootEle = doc.SelectSingleNode ("root");

3.添加子节点元素

    XmlElement bookElement = doc.CreateElement ("book" +i); //创建名字是book的节点 
    XmlElement booknameElement = doc.CreateElement ("bookname" );

    bookElement.AppendChild (booknameElement); //给book添加子节点
    bookElement.AppendChild (bookauthorElement);
    rootEle.AppendChild (bookElement);         //给root添加book节点

4.读取XML 遍历1

    XmlNodeList nodelist = rootEle.ChildNodes;  //容器
	List list = new List ();
	for (int i = 0; i < nodelist.Count; i++) 
	{       XmlNode booknode = nodelist[i];
			XmlNode namenode = booknode["name"];
			string name = namenode.InnerText;		
            string author = nodelist[i]["bookauthor"].InnerText;
			int price = int.Parse( nodelist[i]["bookprice"].InnerText);
            
			Hbook book = new Hbook (name,author,price);
			list.Add(book);
    }

5.替换 遍历2

    foreach (XmlElement item in rootEle.ChildNodes )
	{       Debug.Log (item.Name);
			XmlNode booknamelement = item.SelectSingleNode ("bookname");
			XmlElement replacelement = doc.CreateElement ("name");
			replacelement.InnerText ="aaaa";
			item.ReplaceChild (replacelement, booknamelement); 
           //替换子节点bookname 为 name 
	}

6.保存数据在文件中

    doc.Save (path); 

PlayerPrefs 保存数据

持久化数据,保存在本地, /Library/PlayerPreferences/目录中
只能保存int float string
键值对形式保存

	PlayerPrefs.SetInt ("age", 23);
	PlayerPrefs.SetString ("name", "libiao");
	PlayerPrefs.SetFloat ("score", 98f);

	Debug.Log(PlayerPrefs.GetString("name") + PlayerPrefs.GetInt("age") + PlayerPrefs.GetFloat("score"));
	Debug.Log (PlayerPrefs.GetString ("name", 0)); //没有找到键值对,则返回0


你可能感兴趣的:(Unity3d)