在百度找了3页unity使用XML的相关资料,清一色全是官方的例子,比较繁琐。。于是就使用C#调用XML的方法尝试了一下。
这是第一个例程,测试创建一个简单的XML文件。使用时先调用xmlInit()方法初始化,然后调用writeTest()写入。
可能是我的unity版本问题,程序在build之后xml读写就没用了。
一直没找到解决方法。于是自己写了一个XML类(不支持序列化):http://game.ceeger.com/forum/read.php?tid=4989
如果下面的例程序没用的话,可以换用我写的那个。
- using UnityEngine;
- using System.Collections;
- using System.IO;
- using System.Xml;
- public class XmlTest : MonoBehaviour
- {
- private string fileName = @"/config.xml";
- private string path = "";
- private XmlDocument xd = new XmlDocument();
- private XmlElement rootEle;
- public void xmlInit()
- {
- path = System.IO.Directory.GetCurrentDirectory() + fileName;
- rootEle = xd.CreateElement("root");
- XmlDeclaration xdc = xd.CreateXmlDeclaration("1.0", "GBK", null);//这里是设置XML的版本号,不是自己游戏的版本号
- xd.AppendChild(xdc);
- }
- public void writeTest()
- {
- XmlElement ele = xd.CreateElement("firstXml");
- ele.InnerText = "hi";
- rootEle.AppendChild(ele);
- xd.AppendChild(rootEle);
- xd.Save(path);
- }
- }
复制代码
第二个例程。一个具有读写功能的XML类。用于设置游戏玩家的属性配置文件。并把XmlElement变为结构体。调用更方便。
同样,测试使用时先调用xmlInit(),再调用writeTest()或readTest().
- using UnityEngine;
- using System.Collections;
- using System.IO;
- using System.Xml;
- public class XmlTest : MonoBehaviour
- {
- private string fileName = @"/config.xml";
-
- private string path = "";
-
- private XmlDocument xd = new XmlDocument();
- private XmlElement rootEle;
-
- public void xmlInit()
- {
- path = Directory.GetCurrentDirectory() + fileName;
-
- rootEle = xd.CreateElement("root");
- XmlDeclaration xdc = xd.CreateXmlDeclaration("1.0", "GBK", null);//这里是设置XML的版本号,不是自己游戏的版本号
-
- xd.AppendChild(xdc);
- }
-
-
- public void writeTest()
- {
- string[] players = new string[]{"player1", "player2", "player3"};
- string[] hps = new string[]{"100","200","150"};
- string[] mps = new string[]{"110","62","94"};
- for(int i=0;i <players.Length; i++)
- {
- XmlElement info = xd.CreateElement("info");
- info.SetAttribute("name",players[i]);
- Sct_XmlEles xes = new Sct_XmlEles();
-
- xes.hp = xd.CreateElement("hp");
- xes.hp.InnerText = hps[i];
- xes.mp = xd.CreateElement("mp");
- xes.mp.InnerText = mps[i];
-
- info.AppendChild(xes.hp);
- info.AppendChild(xes.mp);
- rootEle.AppendChild(info);
- }
- xd.AppendChild(rootEle);
- xd.Save(path);
- }
-
- public void readTest()
- {
- string tmpStr = "";
- xd.Load(path);
-
- foreach (XmlNode node1 in xd.ChildNodes)
- {
- foreach (XmlNode node2 in node1.ChildNodes)
- {
- foreach (XmlNode node3 in node2.ChildNodes)
- {
- print (node2.Attributes[0].Name+" ----- "+node2.Attributes[0].Value);
- switch(node3.Name)
- {
- case "hp":
- print ("hp "+node3.InnerText);
- break;
-
- case "mp":
- print ("mp "+node3.InnerText);
- break;
- }
- }
- }
- }
- }
- }
- public struct Sct_XmlEles
- {
- public XmlElement hp;
- public XmlElement mp;
- }
复制代码 |
|
|
|
|
|