1.XML文件数据解析:(首先需要导入XMLParser解析器,The latest released download from:http://dev.grumpyferret.com/unity/)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ROOT>
<table wave="1" enemyname="ground" level="1" wait="3"/>
...
</ROOT>
//XML数据模型类
public class SpawnData { public int wave = 1; public string enemyname = ""; public int level = 1; public float wait = 1.0f; }
//读取XML文件
//存储XML文件 public TextAsset xmldata; //保存读出数据 ArrayList m_enemylist;
void ReadXML() { m_enemylist = new ArrayList(); XMLParser xmlparse = new XMLParser(); XMLNode node = xmlparse.Parse(xmldata.text); XMLNodeList list = node.GetNodeList("ROOT>0>table"); for (int i = 0; i < list.Count; i++) { string wave = node.GetValue("ROOT>0>table>" + i + ">@wave"); string enemyname = node.GetValue("ROOT>0>table>" + i + ">@enemyname"); string level = node.GetValue("ROOT>0>table>" + i + ">@level"); string wait = node.GetValue("ROOT>0>table>" + i + ">@wait"); SpawnData data = new SpawnData(); data.wave = int.Parse(wave); data.enemyname = enemyname; data.level = int.Parse(level); data.wait = float.Parse(wait); m_enemylist.Add(data); } }
2.JSON数据解析(首先需要导入工具LitJSON,下载地址:http://lbv.github.io/litjson//)
1>放到Unity工程中删除文件夹benchmarks和test,在需要数据解析的代码文件中加入:usingLitJson;
2>代码解析:
JSON文件数据如下:
{"name":"中国",
"provinces":[
{"name":"黑龙江","id":1,"citys":["佳木斯","大庆"]},
{"name":"辽宁","id":2,"citys":["沈阳","大连","齐齐哈尔"]},
{"name":"吉林","id":3,"citys":["吉林市","长春市","四平市","哈尔滨"]}
]}
建类:
public class Country { public string name {get; set;} public Province [] provinces; } public class Province { public string name; public int id; public string[] cities; } public TextAsset jsondata;//拖入JSON.txt文件 void ReadJSON() { JsonData jd = JsonMapper.ToObject(jsondata.text); print("p.name" + (string)jd["name"]); JsonData provinces = jd["provinces"]; for(int i = 0; i < provinces.Count; i++) { print("j.name" + provinces[i]["name"]); print("j.cities" + provinces[i]["citys"].Count); for(int j = 0; j < provinces[i]["citys"].Count; j++) { print("provinces[i][citys][" + j + "]" + provinces[i]["citys"][j]); } } }
运行结果如下图:
原文链接:https://www.f2er.com/xml/298533.html