unity序列化和反序列XML,并添加属性

前端之家收集整理的这篇文章主要介绍了unity序列化和反序列XML,并添加属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. usingUnityEngine;
  2. usingSystem.Collections;
  3. usingSystem.Xml;
  4. usingSystem.Xml.Serialization;
  5. usingSystem.IO;
  6. usingSystem.Text;
  7. publicclassReward
  8. {
  9. publicTasktask;
  10. publicAttributeattribute;
  11. publicReward(){}
  12. publicstructTask
  13. {
  14. [XmlAttribute("taskNo")]
  15. publicinttaskNo{get;set;}
  16. [XmlAttribute("taskReward")]
  17. publicinttaskReward{get;set;}
  18. publicIdid1;
  19. publicIdid2;
  20. publicIdid3;
  21. }
  22. publicstructId
  23. [XmlAttribute("flag")]
  24. publicboolflag{get;set;}
  25. [XmlAttribute("name")]
  26. publicstringname{get;set;}
  27. }
  28. publicclassAchievementManager:MonoBehavIoUr{
  29. Rewardreward;
  30. FileInfot;
  31. string_data;
  32. voidStart()
  33. reward=newReward();
  34. t=newFileInfo(Application.dataPath+"\\"+"Achievement.xml");
  35. LoadXML();
  36. reward.task.id1.name="杨纯/nate";
  37. reward.task.id2.name="有点笨";
  38. reward.task.id3.name="dlnuchunge";
  39. Save();
  40. voidLoadXML()
  41. if(t.Exists)
  42. StreamReaderr=t.OpenText();
  43. string_info=r.ReadToEnd();
  44. r.Close();
  45. _data=_info;
  46. if(_data.ToString()!="")
  47. reward=(Reward)DeserializeObject(_data);
  48. publicvoidSave()
  49. _data=SerializeObject(reward);
  50. StreamWriterwriter;
  51. t.Delete();
  52. writer=t.CreateText();
  53. writer.Write(_data);
  54. writer.Close();
  55. stringUTF8ByteArrayToString(byte[]characters)
  56. UTF8Encodingencoding=newUTF8Encoding();
  57. stringconstructedString=encoding.GetString(characters);
  58. return(constructedString);
  59. byte[]StringToUTF8ByteArray(stringpXmlString)
  60. UTF8Encodingencoding=newUTF8Encoding();
  61. byte[]byteArray=encoding.GetBytes(pXmlString);
  62. returnbyteArray;
  63. //HereweserializeourRewardobjectofreward
  64. stringSerializeObject(objectpObject)
  65. stringXmlizedString=null;
  66. MemoryStreammemoryStream=newMemoryStream();
  67. XmlSerializerxs=newXmlSerializer(typeof(Reward));
  68. XmlTextWriterxmlTextWriter=newXmlTextWriter(memoryStream,Encoding.UTF8);
  69. xs.Serialize(xmlTextWriter,pObject);
  70. memoryStream=(MemoryStream)xmlTextWriter.BaseStream;
  71. XmlizedString=UTF8ByteArrayToString(memoryStream.ToArray());
  72. returnXmlizedString;
  73. //Herewedeserializeitbackintoitsoriginalform
  74. objectDeserializeObject(stringpXmlizedString)
  75. XmlSerializerxs=newXmlSerializer(typeof(Reward));
  76. MemoryStreammemoryStream=newMemoryStream(StringToUTF8ByteArray(pXmlizedString));
  77. returnxs.Deserialize(memoryStream);
  78. }

猜你在找的XML相关文章