1. 程式人生 > >Unity 讀取Xml

Unity 讀取Xml

使用 Untiy讀取XML,讀取成功關鍵在與17~19這三行,一定要跳過BOM,要不然就一直獲取不到值。

IEnumerator LoadXml( string filePath, string imageName)
    {
        WWW www = new WWW(filePath);
        yield return www;
        //Debug.Log(www.text);

        if (www.error != null)
        {
            print("The request failed");
        }
        else
        {
            print("The request is successful");
            //建立
            XmlDocument XmlDoc = new XmlDocument();
            //跳過BOM 
            System.IO.StringReader stringReader = new System.IO.StringReader(www.text);
            stringReader.Read();
            string result = stringReader.ReadToEnd();
            //關閉
            stringReader.Close();

            //載入文字
            XmlDoc.LoadXml(result);

            //獲取節點個數
            int XmlCount = XmlDoc.GetElementsByTagName("JD").Count;

            for (int i = 0; i < XmlCount; i++)
            {
                if (XmlDoc.GetElementsByTagName("Name")[i].InnerText == imageName)
                {
                    string Name = XmlDoc.GetElementsByTagName("Name")[i].InnerText;
                    string Path = XmlDoc.GetElementsByTagName("Path")[i].InnerText;

                }
            }
        }
    }

 

XML文字

<?xml version="1.0" encoding="utf-8" ?>
<Xml>
  <JD>
    <Name>A</Name>
    <Path>http://-------</Path>
  </JD>
  <JD>
    <Name>B</Name>
    <Path>http://-------</Path>
  </JD>
</Xml>