纳金网

标题: Unity3d中写入XML文件 [打印本页]

作者: 王者再临    时间: 2014-11-30 07:48
标题: Unity3d中写入XML文件
Unity3d中写入XML文件
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.IO;
  4. using System.Xml;
  5. public class PlayerXMLWriter
  6. {

  7.     string _filePath;
  8.     XmlDocument _xmlDoc;
  9.     XmlElement _elRoot;

  10.     public PlayerXMLWriter(string filePath)
  11.     {
  12.         _filePath=filePath;
  13.         _xmlDoc=new XmlDocument();
  14.         if(File.Exists(_filePath)){
  15.             _xmlDoc.Load(_filePath);
  16.             _elRoot = _xmlDoc.DocumentElement;
  17.             _elRoot.RemoveAll();
  18.         }
  19.         else
  20.         {
  21.             _elRoot = _xmlDoc.CreateElement("xxx");
  22.             _xmlDoc.AppendChild(_elRoot);
  23.         }
  24.     }


  25.     public void SaveXMLFile()
  26.     {
  27.         _xmlDoc.Save(_filePath);
  28.     }
  29.         // Use this for initialization
  30.         public void AddXMLElement(string playerName,string playerScore)
  31.     {
  32.         XmlElement elPlayer = _xmlDoc.CreateElement("xxx");
  33.         _elRoot.AppendChild(elPlayer);

  34.         XmlElement elName = _xmlDoc.CreateElement("xxx");
  35.         elName.InnerText = playerName;
  36.         elPlayer.AppendChild(elName);

  37.         XmlElement elScore = _xmlDoc.CreateElement("xxxx");
  38.         elScore.InnerText = playerScore;
  39.         elScore.SetAttribute("xxx","xxxx");
  40.         elPlayer.AppendChild(elScore);
  41.     }
  42. }

  43. 在unity中使用:
  44. string fileName="playerData.xml";
  45. string folderName="Data";

  46. void Start()
  47. {
  48.      string filePath=Application.dataPath+Path.DirectorySeparatorChar+fileName;
  49.      PlayerXMLWriter myPlayerXMLWriter=new  PlayerXMLWriter(filePath);
  50.      myPlayerXMLWriter.AddElement("matt","55");
  51.      myPlayerXMLWriter.SaveXMLFile();
  52. }
复制代码





欢迎光临 纳金网 (http://go.narkii.com/club/) Powered by Discuz! X2.5