Unity读取xml文件

在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"));
        }

    }
}
posted @   马林林林  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示