Unity3D开发之XML解析

来源:互联网 发布:生物医药上市知乎 编辑:程序博客网 时间:2024/06/07 20:31

XML文件的解析类似游戏中配置文件的更改。在程序外部就可以更改程序运行模式。好了,上代码,这是解析xml的通用类。

using System.Collections.Generic;using System.IO;using System.Xml;using UnityEngine;/// <summary>/// 读取配置文件/// </summary>public class LoadXml{    public static string xmlPath = Application.streamingAssetsPath + "/Id.config";    public static readonly object _lockHelper = new object();    public static XmlDocument _xml = new XmlDocument();    public static void Open()    {        if (File.Exists(xmlPath))        {            _xml.Load(xmlPath);            //Debug.Log("open id.config successful");        }                }    public static List<string> returnValue()    {        lock (_lockHelper)        {            Open();            XmlNode id = _xml.SelectSingleNode("/root/ID");            List<string> valueList = new List<string>();            foreach (XmlNode xl in id.ChildNodes)            {                valueList.Add(xl.InnerText);                //Debug.Log(xl.InnerText);            }            return valueList;        }    }    public static string getValue(string s)    {        lock (_lockHelper)        {            Open();            s = "/root/" + s.Replace(".", "/");            XmlNode id = _xml.SelectSingleNode(s);            Debug.Log(id.InnerText.Trim());            return id.InnerText.Trim();        }    }    public static Dictionary<string, string> returnHRZParameter()    {        lock (_lockHelper)        {            Open();            XmlNode hrzId = _xml.SelectSingleNode("/root/HRZID");            //Debug.Log(hrzId.ChildNodes.Count);            Dictionary<string, string> parameterDic = new Dictionary<string, string>();            if (hrzId.ChildNodes.Count>0)            {                foreach (XmlNode parameter in hrzId.ChildNodes)                {                    XmlElement _parameter = (XmlElement)parameter;                    if (parameterDic.ContainsKey(_parameter.GetAttribute("name").Trim()))                    {                        Debug.LogError(_parameter.GetAttribute("name").Trim());                        return null;                    }                    if (!Globle.IsExcute)                    {                        Globle.IsExcute = true;                        Globle.IdValue = _parameter.GetAttribute("id").Trim();                    }                    parameterDic.Add(_parameter.GetAttribute("name").Trim(), _parameter.GetAttribute("id").Trim());                }                return parameterDic;            }            return null;        }    }}
对应的配置文件格式如下:

希望对你有帮助。双击评论666哈哈

原创粉丝点击