在PC上和IOS上讀取XML文件的方式略有差別,經測試,IOS上不支持如下方法載入XML文件:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Assets/Resources/text.xml");
IOS上載入XML的正確方法有2種:
(1)方法一
TextAsset textAsset = (TextAsset)Resources.Load(filename, typeof(TextAsset));
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(new StringReader(textAsset.text));
(2)方法二
TextAsset textAsset = (TextAsset)Resources.Load(filename, typeof(TextAsset));
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXML(textAsset.text);
上述2種方法分別使用了XmlDocument的Load()方法和LoadXML()方法,傳入的參數有些差別,不過都需要通過Resources.Load()方法先將文件載入到一個TextAsset中,然后傳給xmlDoc的載入方法。
(3)方法三
需要在IPad上進行持久化操作的文件,比如游戲的本地存檔等數據,是不能存放在Resources目錄下的,因為IPad上沒法對其進行寫操作。
那么對於IPad上讀寫XML,應該怎樣進行操作呢?方法如下所述:
將需要序列化的文件存放在Application.persistentDataPath目錄下,該目錄是一個平台相關的路徑。
寫:
XmlDocument xmlDoc = new XmlDocument();
...
xmlDoc.Save(Application.persistentDataPath+"//abc.xml");
讀:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Application.persistentDataPath+"//abc.xml");
PS1:還有另外一種實現本地持久化操作的方法,使用PlayerPrefs類,此類是U3D提供的專門用來進行玩家偏好設置的類,不過偶暫時未使用此類,是否方便尚未測試。
PS2:
對於Android平台:使用上述方法(3),即和IOS平台相同的操作即可。
對於Mac平台:使用上述方法(1)/(2)。
對於Windows平台:使用上述方法(1)/(2)。