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);
}
}
這樣就可以在完成初始化的時候進行調用;
結果: