unity 读取xml 信息

前端之家收集整理的这篇文章主要介绍了unity 读取xml 信息前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、首先在unity工程中Resources/XML目录下创建xml文件:xmls.xml;

如:

<?xml version ="1.0" encoding = "utf-8"?>
<root>
	<parent name ="Lily">
		<child name ="L01">123</child>
		<child name ="L02">apple</child>
		<child name ="L03">大</child>
	</parent>
</root>

2、定义我们需要的变量:

using System.Xml;

private XmlDocument xmldoc;
private XmlNode root;
private string url;

3、在Start()函数进行初始化:

初始化方法一:

url = Application.dataPath + "/Resources/XML/xmls.xml";
xmldoc = new XmlDocument();
xmldoc.Load(url);
root = xmldoc.SelectSingleNode("root");

初始化方法二:

url = "XML/xmls";
xmlAsset = Resources.Load<TextAsset>(url);
xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlAsset.text);

初始化完成之后、来写我们需要的方法

4、读取Lily:

void ReadLily()
	{
		XmlElement parent = (XmlElement)root.SelectSingleNode("parent");
		Debug.Log(parent.Name + "Name:" + parent.GetAttribute("name"));
	}

5、读取所有子节点的值:

void ReadAllChildName()
	{
		XmlNode parent = root.SelectSingleNode("parent");
		XmlNodeList childs = parent.SelectNodes("child");
		foreach (XmlNode temp in childs)
		{
			XmlElement ele = (XmlElement)temp;
			Debug.Log(ele.Name + "Name:" + ele.GetAttribute("name") + "    value:" + ele.InnerText);
		}
	}

这样就可以在完成初始化的时候进行调用

结果:

猜你在找的XML相关文章