1. 程式人生 > >Unity3D-載入XML配置表文件

Unity3D-載入XML配置表文件

//XMLFile1.xml
<root>
    <goods>
        <item type = "1">
            <param>10001</param>
            <param>5</param>
        </item>
        <item type = "3">
            <param>10004</param>
            <param>10</param>
        </item
>
<goods> </root>
using System.Xml; //匯入名稱空間

public class XmlDataGoods
{
    public int type;
    public int[] param;
}

public List<XmlDataGoods> LoadXml()
{
    List<XmlDataGoods> data = new List<XmlDataGoods>();
    XmlDocument doc = new XmlDocument(); //例項化XML文件物件
doc.Load("XMLFile1.xml"); //載入XML檔案,注意反斜槓和字尾名 XmlNode root = doc.SelectSingleNode("goods"); //獲取<root>下的<goods>節點 XmlNodeList nodeList = root.SelectNodes("item");//獲取<goods>下的所有<item>節點 for (int i = 0; i < nodeList.Count; ++i) { XmlDataGoods goods = new
XmlDataGoods(); XmlNode node = nodeList[i]; XmlElement element = (XmlElement)node;//節點轉化為元素 goods.type = Convert.ToInt32(element.GetAttribute("type"));//獲取<item>節點的type屬性值 XmlNodeList childNodes = node.ChildNodes;//獲取<item>下的所有子節點 goods.param = new int[childNodes.Count]; for (int j = 0; j < childNodes.Count; ++j) { goods.param[j] = Convert.ToInt32(childNodes[j].InnerText);//獲取子節點的串聯值 } data.Add(goods); } return data; }