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);
}
}
}
}
有问题欢迎留言,谢谢!