unity Xml文件的读取

首先吧需要读取的文件放到该目录下。(我这里读取的是名为item的文件),注意字母不要打错。
在这里插入图片描述
这里是item里面的内容

<item>
  <item1>
    <id>1</id>
    <name>china</name>
    <year>2016</year>
  </item1>
  <item2>
    <id>2</id>
    <name>usa</name>
    <year>2017</year>
  </item2>
</item>

接着进行读取XML

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
using System.IO;

public class XMLSlote : MonoBehaviour
{
    void Start()
    {
        parseXml();
    }

    //解析xml
    void parseXml()
    {
        //也可以前面加上@,区别就是有@的话,双引号里面的内容不转义,比如" \" "
        //string filePath = Application.dataPath+@"/Resources/item.xml";
        string filePath = Application.dataPath + "/Resources/item.xml";
        if (File.Exists(filePath))
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filePath);
            XmlNodeList node = xmlDoc.SelectSingleNode("item").ChildNodes;
            //遍历节点
            foreach (XmlElement ele in node)
            {
                //item下面的节点

                if (ele.Name == "item1")
                {
                    foreach (XmlElement i1 in ele.ChildNodes)
                    {
                        if (i1.Name == "id")
                        {
                            Debug.Log("i1.id"+i1.InnerText);
                        }
                        if (i1.Name == "name")
                        {
                            Debug.Log("i1.name" + i1.InnerText);
                        }
                        if (i1.Name == "year")
                        {
                            Debug.Log("i1.year" + i1.InnerText);
                        }
                    }
                }
                if (ele.Name == "item2")
                {
                    foreach (XmlElement i2 in ele.ChildNodes)
                    {
                        if (i2.Name == "id")
                        {
                            Debug.Log("i2 id" + i2.InnerText);
                        }
                        if (i2.Name == "name")
                        {
                            Debug.Log("i2.name" + i2.InnerText);
                        }
                        if (i2.Name == "year")
                        {
                            Debug.Log("i2.year" + i2.InnerText);
                        }
                    }
                }
            }
        }
    }
}

最终输出来的结果是
在这里插入图片描述
参考:https://blog.csdn.net/qq_40544338/article/details/88714870

发布了35 篇原创文章 · 获赞 3 · 访问量 2044

猜你喜欢

转载自blog.csdn.net/weixin_43333566/article/details/104186352
今日推荐