Save and Load from XML【转】

Save and Load from XML

保存工程的信息:比如游戏进程中的位置信息,对抗双方的个人信息等:

方法1:使用xml文件:

 xml文件要以UTF-8的格式存储;

 但是这样做会使得programmer 可以从脚本中控制xml文件中的所有的字符,包括xml文件中的语法命令字符,因此会带来不安全隐患;

 附上两段代码:

 A 这一段是我自己写的,将一个xml文件按照字符串读入;

虽然unity3d中的string类型说明中讲到保存的是unicode characters,但是实际上当xml文件比较大的时候,如果保存成unicode,就读不出来,如果保存成UTF-8就不存在这个问题;

C#版本:

[c-sharp] view plaincopy
  1. using UnityEngine;   
  2. using System.Collections;   
  3. using System.Xml;   
  4. using System.Xml.Serialization;   
  5. using System.IO;   
  6. using System.Text;   
  7. public class ReadXML: MonoBehaviour {  
  8.    
  9.  //store the read in file   
  10.  WWW statusFile;  
  11.    
  12.  //decide wether the reading of  xml has been finished  
  13.     bool isReadIn = false;  
  14.  // Use this for initialization  
  15.  IEnumerator Start () {//不能用void,否则没有办法使用yield  
  16.   isReadIn = false;  
  17.   yield return StartCoroutine(ReadIn());  
  18.   isReadIn = true;  
  19.  }  
  20.    
  21.  IEnumerator ReadIn()  
  22.  {  
  23.   yield return statusFile = new WWW("file:///D:/unity/rotationAndcolor/Assets/information/testxml.xml");//注意路径的写法  
  24.  }  
  25.    
  26.  // Update is called once per frame  
  27.  void Update () {  
  28.   if(isReadIn)  
  29.   {  
  30.    string statusData = statusFile.data;  
  31.    print(statusData.Length);  
  32.    }  
  33.  }  
  34.    
  35.  //get the parameters in the xml file  
  36.  void getPatameters(string _xmlString)  
  37.  {  
  38.   //_xmlString.[0]   
  39.   }  
  40.    
  41.  void postParameters()  
  42.  {  
  43.     
  44.   }  
  45. }  
  46. public class _GameSaveLoad: MonoBehaviour {   
  47.    // An example where the encoding can be found is at   
  48.    // http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp   
  49.    // We will just use the KISS method and cheat a little and use   
  50.    // the examples from the web page since they are fully described   
  51.       
  52.    // This is our local private members   
  53.    Rect _Save, _Load, _SaveMSG, _LoadMSG;   
  54.    bool _ShouldSave, _ShouldLoad,_SwitchSave,_SwitchLoad;   
  55.    string _FileLocation,_FileName;   
  56.    public GameObject _Player;   
  57.    UserData myData;   
  58.    string _PlayerName;   
  59.    string _data;   
  60.       
  61.    Vector3 VPosition;   
  62.       
  63.    // When the EGO is instansiated the Start will trigger   
  64.    // so we setup our initial values for our local members   
  65.    void Start () {   
  66.       // We setup our rectangles for our messages   
  67.       _Save=new Rect(10,80,100,20);   
  68.       _Load=new Rect(10,100,100,20);   
  69.       _SaveMSG=new Rect(10,120,400,40);   
  70.       _LoadMSG=new Rect(10,140,400,40);   
  71.           
  72.       // Where we want to save and load to and from   
  73.       _FileLocation=Application.dataPath;   
  74.       _FileName="SaveData.xml";   
  75.       
  76.       // for now, lets just set the name to Joe Schmoe   
  77.       _PlayerName = "Joe Schmoe";   
  78.           
  79.       // we need soemthing to store the information into   
  80.       myData=new UserData();   
  81.    }   
  82.       
  83.    void Update () {}   
  84.       
  85.    void OnGUI()   
  86.    {      
  87.          
  88.    //***************************************************   
  89.    // Loading The Player...   
  90.    // **************************************************         
  91.    if (GUI.Button(_Load,"Load")) {   
  92.          
  93.       GUI.Label(_LoadMSG,"Loading from: "+_FileLocation);   
  94.       // Load our UserData into myData   
  95.       LoadXML();   
  96.       if(_data.ToString() != "")   
  97.       {   
  98.         // notice how I use a reference to type (UserData) here, you need this   
  99.         // so that the returned object is converted into the correct type   
  100.         myData = (UserData)DeserializeObject(_data);   
  101.         // set the players position to the data we loaded   
  102.         VPosition=new Vector3(myData._iUser.x,myData._iUser.y,myData._iUser.z);                
  103.         _Player.transform.position=VPosition;   
  104.         // just a way to show that we loaded in ok   
  105.         Debug.Log(myData._iUser.name);   
  106.       }   
  107.       
  108.    }   
  109.       
  110.    //***************************************************   
  111.    // Saving The Player...   
  112.    // **************************************************      
  113.    if (GUI.Button(_Save,"Save")) {   
  114.                 
  115.      GUI.Label(_SaveMSG,"Saving to: "+_FileLocation);   
  116.      myData._iUser.x=_Player.transform.position.x;   
  117.      myData._iUser.y=_Player.transform.position.y;   
  118.      myData._iUser.z=_Player.transform.position.z;   
  119.      myData._iUser.name=_PlayerName;      
  120.             
  121.      // Time to creat our XML!   
  122.      _data = SerializeObject(myData);   
  123.      // This is the final resulting XML from the serialization process   
  124.      CreateXML();   
  125.      Debug.Log(_data);   
  126.    }   
  127.       
  128.       
  129.    }   
  130.       
  131.    /* The following metods came from the referenced URL */   
  132.    string UTF8ByteArrayToString(byte[] characters)   
  133.    {        
  134.       UTF8Encoding encoding = new UTF8Encoding();   
  135.       string constructedString = encoding.GetString(characters);   
  136.       return (constructedString);   
  137.    }   
  138.       
  139.    byte[] StringToUTF8ByteArray(string pXmlString)   
  140.    {   
  141.       UTF8Encoding encoding = new UTF8Encoding();   
  142.       byte[] byteArray = encoding.GetBytes(pXmlString);   
  143.       return byteArray;   
  144.    }   
  145.       
  146.    // Here we serialize our UserData object of myData   
  147.    string SerializeObject(object pObject)   
  148.    {   
  149.       string XmlizedString = null;   
  150.       MemoryStream memoryStream = new MemoryStream();   
  151.       XmlSerializer xs = new XmlSerializer(typeof(UserData));   
  152.       XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);   
  153.       xs.Serialize(xmlTextWriter, pObject);   
  154.       memoryStream = (MemoryStream)xmlTextWriter.BaseStream;   
  155.       XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());   
  156.       return XmlizedString;   
  157.    }   
  158.       
  159.    // Here we deserialize it back into its original form   
  160.    object DeserializeObject(string pXmlizedString)   
  161.    {   
  162.       XmlSerializer xs = new XmlSerializer(typeof(UserData));   
  163.       MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));   
  164.       XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);   
  165.       return xs.Deserialize(memoryStream);   
  166.    }   
  167.       
  168.    // Finally our save and load methods for the file itself   
  169.    void CreateXML()   
  170.    {   
  171.       StreamWriter writer;   
  172.       FileInfo t = new FileInfo(_FileLocation+"//"+ _FileName);   
  173.       if(!t.Exists)   
  174.       {   
  175.          writer = t.CreateText();   
  176.       }   
  177.       else   
  178.       {   
  179.          t.Delete();   
  180.          writer = t.CreateText();   
  181.       }   
  182.       writer.Write(_data);   
  183.       writer.Close();   
  184.       Debug.Log("File written.");   
  185.    }   
  186.       
  187.    void LoadXML()   
  188.    {   
  189.       StreamReader r = File.OpenText(_FileLocation+"//"+ _FileName);   
  190.       string _info = r.ReadToEnd();   
  191.       r.Close();   
  192.       _data=_info;   
  193.       Debug.Log("File Read");   
  194.    }   
  195. }   
  196. // UserData is our custom class that holds our defined objects we want to store in XML format   
  197.  public class UserData   
  198.  {   
  199.     // We have to define a default instance of the structure   
  200.    public DemoData _iUser;   
  201.     // Default constructor doesn't really do anything at the moment   
  202.    public UserData() { }   
  203.       
  204.    // Anything we want to store in the XML file, we define it here   
  205.    public struct DemoData   
  206.    {   
  207.       public float x;   
  208.       public float y;   
  209.       public float z;   
  210.       public string name;   
  211.    }   

 

 

js 版本:

[javascript] view plaincopy
  1. import System;  
  2. import System.Collections;  
  3. import System.Xml;  
  4. import System.Xml.Serialization;  
  5. import System.IO;  
  6. import System.Text;  
  7. // Anything we want to store in the XML file, we define it here  
  8. class DemoData  
  9. {  
  10.     var x : float;  
  11.     var y : float;  
  12.     var z : float;  
  13.     var name : String;  
  14. }  
  15. // UserData is our custom class that holds our defined objects we want to store in XML format  
  16.  class UserData  
  17.  {  
  18.     // We have to define a default instance of the structure  
  19.    public var _iUser : DemoData = new DemoData();  
  20.     // Default constructor doesn't really do anything at the moment  
  21.    function UserData() { }  
  22. }  
  23. //public class GameSaveLoad: MonoBehaviour {  
  24. // An example where the encoding can be found is at  
  25. // http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp  
  26. // We will just use the KISS method and cheat a little and use  
  27. // the examples from the web page since they are fully described  
  28. // This is our local private members  
  29. private var _Save : Rect;  
  30. private var _Load : Rect;  
  31. private var _SaveMSG : Rect;  
  32. private var _LoadMSG : Rect;  
  33. //var _ShouldSave : boolean;  
  34. //var _ShouldLoad : boolean;  
  35. //var _SwitchSave : boolean;  
  36. //var _SwitchLoad : boolean;  
  37. private var _FileLocation : String;  
  38. private var _FileName : String = "SaveData.xml";  
  39. //public GameObject _Player;  
  40. var _Player : GameObject;  
  41. var _PlayerName : String = "Joe Schmoe";  
  42. private var myData : UserData;  
  43. private var _data : String;  
  44. private var VPosition : Vector3;  
  45. // When the EGO is instansiated the Start will trigger  
  46. // so we setup our initial values for our local members  
  47. //function Start () {  
  48. function Awake () {   
  49.       // We setup our rectangles for our messages  
  50.       _Save=new Rect(10,80,100,20);  
  51.       _Load=new Rect(10,100,100,20);  
  52.       _SaveMSG=new Rect(10,120,200,40);  
  53.       _LoadMSG=new Rect(10,140,200,40);  
  54.          
  55.       // Where we want to save and load to and from  
  56.       _FileLocation=Application.dataPath;  
  57.         
  58.             
  59.       // we need soemthing to store the information into  
  60.       myData=new UserData();  
  61.    }  
  62.      
  63. function Update () {}  
  64.      
  65. function OnGUI()  
  66. {     
  67.    // ***************************************************  
  68.    // Loading The Player...  
  69.    // **************************************************         
  70.    if (GUI.Button(_Load,"Load")) {  
  71.         
  72.       GUI.Label(_LoadMSG,"Loading from: "+_FileLocation);  
  73.       // Load our UserData into myData  
  74.       LoadXML();  
  75.       if(_data.ToString() != "")  
  76.       {  
  77.          // notice how I use a reference to type (UserData) here, you need this  
  78.          // so that the returned object is converted into the correct type  
  79.          //myData = (UserData)DeserializeObject(_data);  
  80.          myData = DeserializeObject(_data);  
  81.          // set the players position to the data we loaded  
  82.          VPosition=new Vector3(myData._iUser.x,myData._iUser.y,myData._iUser.z);               
  83.          _Player.transform.position=VPosition;  
  84.          // just a way to show that we loaded in ok  
  85.          Debug.Log(myData._iUser.name);  
  86.       }  
  87.      
  88.    }  
  89.      
  90.    // ***************************************************  
  91.    // Saving The Player...  
  92.    // **************************************************     
  93.    if (GUI.Button(_Save,"Save")) {  
  94.               
  95.       GUI.Label(_SaveMSG,"Saving to: "+_FileLocation);  
  96.       //Debug.Log("SaveLoadXML: sanity check:"+ _Player.transform.position.x);  
  97.         
  98.       myData._iUser.x = _Player.transform.position.x;  
  99.       myData._iUser.y = _Player.transform.position.y;  
  100.       myData._iUser.z = _Player.transform.position.z;  
  101.       myData._iUser.name = _PlayerName;     
  102.           
  103.       // Time to creat our XML!  
  104.       _data = SerializeObject(myData);  
  105.       // This is the final resulting XML from the serialization process  
  106.       CreateXML();  
  107.       Debug.Log(_data);  
  108.    }  
  109. }  
  110.      
  111. /* The following metods came from the referenced URL */  
  112. //string UTF8ByteArrayToString(byte[] characters)  
  113. function UTF8ByteArrayToString(characters : byte[] )  
  114. {       
  115.    var encoding : UTF8Encoding  = new UTF8Encoding();  
  116.    var constructedString : String  = encoding.GetString(characters);  
  117.    return (constructedString);  
  118. }  
  119. //byte[] StringToUTF8ByteArray(string pXmlString)  
  120. function StringToUTF8ByteArray(pXmlString : String)  
  121. {  
  122.    var encoding : UTF8Encoding  = new UTF8Encoding();  
  123.    var byteArray : byte[]  = encoding.GetBytes(pXmlString);  
  124.    return byteArray;  
  125. }  
  126.      
  127.    // Here we serialize our UserData object of myData  
  128.    //string SerializeObject(object pObject)  
  129. function SerializeObject(pObject : Object)  
  130. {  
  131.    var XmlizedString : String  = null;  
  132.    var memoryStream : MemoryStream  = new MemoryStream();  
  133.    var xs : XmlSerializer = new XmlSerializer(typeof(UserData));  
  134.    var xmlTextWriter : XmlTextWriter  = new XmlTextWriter(memoryStream, Encoding.UTF8);  
  135.    xs.Serialize(xmlTextWriter, pObject);  
  136.    memoryStream = xmlTextWriter.BaseStream; // (MemoryStream)  
  137.    XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());  
  138.    return XmlizedString;  
  139. }  
  140.    // Here we deserialize it back into its original form  
  141.    //object DeserializeObject(string pXmlizedString)  
  142. function DeserializeObject(pXmlizedString : String)     
  143. {  
  144.    var xs : XmlSerializer  = new XmlSerializer(typeof(UserData));  
  145.    var memoryStream : MemoryStream  = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));  
  146.    var xmlTextWriter : XmlTextWriter  = new XmlTextWriter(memoryStream, Encoding.UTF8);  
  147.    return xs.Deserialize(memoryStream);  
  148. }  
  149.    // Finally our save and load methods for the file itself  
  150. function CreateXML()  
  151. {  
  152.    var writer : StreamWriter;  
  153.    //FileInfo t = new FileInfo(_FileLocation+"//"+ _FileName);  
  154.    var t : FileInfo = new FileInfo(_FileLocation+"/"+ _FileName);  
  155.    if(!t.Exists)  
  156.    {  
  157.       writer = t.CreateText();  
  158.    }  
  159.    else  
  160.    {  
  161.       t.Delete();  
  162.       writer = t.CreateText();  
  163.    }  
  164.    writer.Write(_data);  
  165.    writer.Close();  
  166.    Debug.Log("File written.");  
  167. }  
  168.      
  169. function LoadXML()  
  170. {  
  171.    //StreamReader r = File.OpenText(_FileLocation+"//"+ _FileName);  
  172.    var r : StreamReader = File.OpenText(_FileLocation+"/"+ _FileName);  
  173.    var _info : String = r.ReadToEnd();  
  174.    r.Close();  
  175.    _data=_info;  
  176.    Debug.Log("File Read");  
  177. }  
  178. //} 

 

方法2:使用unity 3d 的ISerializable类

 

它的好处是,可以将文件存成自己定义的后缀形式,并且2进制化存储,在u3d的帮助文档中有相关介绍。

 

 

posted @ 2012-02-26 17:19  渡蓝  阅读(307)  评论(0)    收藏  举报