在XML中配置字典名称,字典的key和value,目前key和value都是用的string类型,通过ParseXml类的ParseData函数,传递字典名称和key来获取value
xml文件内容
解析数据类
using UnityEngine;
using System.Xml;
using System;/// <summary>
/// 读取xml信息类
/// </summary>
public class ParseXml
{private string xmlPath = "Assets/Configs/FormInfo.xml";/// <summary>/// 解析数据/// </summary>/// <param name="dictionary">要解析的字典</param>/// <param name="key">键</param>/// <returns></returns>public string ParseData(string dictionary, string key){try{XmlDocument xmlDocument = new XmlDocument();//加载配置文件xmlDocument.Load(xmlPath);XmlNode xmlRoot = xmlDocument.SelectSingleNode("Body");//加载字典列表XmlNodeList xmlDictionaryList = xmlRoot.ChildNodes;//遍历字典列表for(int i = 0; i < xmlDictionaryList.Count; i++){XmlNode xmlDictionary = xmlDictionaryList.Item(i);if(xmlDictionary.Name != dictionary){continue;}//加载字典项XmlNodeList xmlRootLists = xmlDictionary.ChildNodes;//遍历字典项for(int j = 0; j < xmlRootLists.Count; j++){XmlNode rootNode = xmlRootLists.Item(j);//获取字典项string k = rootNode.Attributes.GetNamedItem("Key").Value;string v = rootNode.Attributes.GetNamedItem("Value").Value;if (key == k){return v;}}}}catch(Exception e){Debug.Log(e);return null;}Debug.Log("NotFound");return null;}
}
调用例子
using UnityEngine;public class GetXml : MonoBehaviour
{ParseXml parseXml = new ParseXml();void Update(){if (Input.GetKeyDown(KeyCode.Q)){Debug.Log(parseXml.ParseData("Dialogs", "1"));}if (Input.GetKeyDown(KeyCode.W)){Debug.Log(parseXml.ParseData("Tips", "1"));}}
}