Unity解析XML 《二》

unity 在編輯器模式下可以使用序列化和反序列化的方式解析XML
但是如果到了IOS平臺,使用反序列化的可能會導致錯誤,
建議使用解析XML的方式

xml文件如下:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<item ID="1">
		<videoName>north_and_south</videoName>
		<vid>c617df497466e5c60ca484ad9e0195b1_c</vid>
	</item>
	<item ID="2">
		<videoName>yangtze_river_delta</videoName>
		<vid>c617df497426087edda25545b6f74f47_c</vid>
	</item>
	<item ID="3">
		<videoName>xinjiang_geography</videoName>
		<vid>c617df4974e3d5453828f8cb9f57924d_c</vid>
	</item>
	<item ID="4">
		<videoName>taiwan_economy</videoName>
		<vid>c617df4974aaebf8879cb13b5abce028_c</vid>
	</item>
</root>

解析代碼:

  public static Dictionary<string, string>  ParseVidCfg(string path,string rootName)
    {
        Dictionary<string, string> vidDic = new Dictionary<string, string>();

        XmlDocument doc = new XmlDocument();
        doc.Load(path);
        XmlNodeList nodlist = doc.SelectSingleNode(rootName).ChildNodes;

        for(int i = 0; i < nodlist.Count; i++)
        {
            XmlNodeList nodeList= nodlist[i].ChildNodes;
            string vid = string.Empty;
            string videoName = string.Empty;
            for (int j = 0; j < nodeList.Count; j++)
            {             
                switch (nodeList[j].Name)
                {
                    case "videoName":
                        videoName = nodeList[j].InnerText;
                    break;
                    case "vid":
                        vid = nodeList[j].InnerText;
                        break;
                }                                
            }

            if(!string.IsNullOrEmpty(vid) && !string.IsNullOrEmpty(videoName))
            {
                vidDic.Add(videoName,vid);
            }
        }



        return vidDic;
    }

調用代碼

 public Dictionary<string, string> vidDic = new Dictionary<string, string>();
 vidDic= LoadXML.ParseVidCfg(FileServer.Instance.PathDeal(ConstConfig.vidCfgPath), "root");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章