Unity里面加载读取XML文件数据

1.新建XML源文件

<person>
  <item id="1" name="张三" sex="女" age="20"/>
  <item id="2" name="李四" sex="男" age="25"/>
  <item id="3" name="王五" sex="女" age="18"/>
</person>

2.创建数据类

using UnityEngine;
using System.Collections;
using System.Xml;
namespace Com.Rainier.WangJing
{
       public class Person
       {
        public string Id;
        public string Name;
        public string Sex;
        public string Age;
           public Person(XmlElement xmlElement)
        {
            Id = xmlElement.GetAttribute("id");
            Name = xmlElement.GetAttribute("name");
            Sex = xmlElement.GetAttribute("Sex");
            Age = xmlElement.GetAttribute("Age");
        }
    }
}

3.读取XML文件代码

******************************************************************************/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
namespace Com.Rainier.WangJing
{
       public sealed class XmlReader:MonoBehaviour
    {
        public static readonly XmlReader Instance = new XmlReader();
        private XmlReader() { }
        //以上为内联函数初始化(生成的同时初始化)的单例模式,它等同于
        //public static readonly XmlReader instance;
        静态构造函数,CLR只执行一次
        //static XmlReader()
        //{
        //    instance = new XmlReader();
        //}
        私有构造函数,防止外界调用
        //private XmlReader() { }
        public List<Person> person;
        void Start ()
              {
            person = new List<Person>();
            TextAsset textAsset = Resources.Load<TextAsset>("Table/Person");
            if(textAsset)
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(textAsset.text);
                //获取person标签下的所有子节点
                XmlNodeList xmlNodeList =  xmlDocument.SelectSingleNode("person").ChildNodes;
                foreach(XmlElement element in xmlNodeList)
                {
                    person.Add(new Person(element));
                }
            }
            for(int i=0;i< person.Count;i++)
            {
                Debug.Log("第"+(i+1)+"条数据为:"+"id--"+ person[i].Id + "name--" +  person[i].Name+"sex--" + person[i].Sex + "age--" + person[i].Age);
            }
        }             
       }
}

有问题欢迎留言,谢谢!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值