It is possible to create an XML data structure and then save that data directly to a text file using the XMLDocument.Save()
method; this recipe illustrates how.
To save XML data to text files directly, perform the following steps:
PlayerXMLWriter
:// file: PlayerXMLWriter.cs using System.Text; using System.Xml; using System.IO; public class PlayerXMLWriter { private string _filePath; private XmlDocument _xmlDoc; private XmlElement _elRoot; public PlayerXMLWriter(string filePath) { _filePath = filePath; _xmlDoc = new XmlDocument(); if(File.Exists (_filePath)) { _xmlDoc.Load(_filePath); _elRoot = _xmlDoc.DocumentElement; _elRoot.RemoveAll(); } else { _elRoot = _xmlDoc.CreateElement("playerScoreList"); _xmlDoc.AppendChild(_elRoot); } } public void SaveXMLFile() { _xmlDoc.Save(_filePath); } public void AddXMLElement(string playerName, string playerScore) { XmlElement elPlayer = _xmlDoc.CreateElement("playerScore"); _elRoot.AppendChild(elPlayer); XmlElement elName = _xmlDoc.CreateElement("name"); elName.InnerText = playerName; elPlayer.AppendChild(elName); XmlElement elScore = _xmlDoc.CreateElement("score"); elScore.InnerText = playerScore; elPlayer.AppendChild(elScore); } }
// file: CreateXMLTextFile.cs using UnityEngine; using System.Collections; using System.IO; public class CreateXMLTextFile : MonoBehaviour { public string fileName = "playerData.xml"; public string folderName = "Data"; private void Start() { string filePath = Application.dataPath + Path.DirectorySeparatorChar + fileName; PlayerXMLWriter myPlayerXMLWriter = new PlayerXMLWriter(filePath); myPlayerXMLWriter.AddXMLElement("matt", "55"); myPlayerXMLWriter.AddXMLElement("jane", "99"); myPlayerXMLWriter.AddXMLElement("fred", "101"); myPlayerXMLWriter.SaveXMLFile(); print( "XML file should now have been created at: " + filePath); } }
playerData.xml
in the Data
folder of your project's standalone files, containing the XML data for the three players:playerData.xml
file should be the XML player list data:The Start()
method creates myPlayerXMLWriter
, a new object of the PlayerXMLWriter
class, to which it passes the new, required XML text file filePath
as an argument. Three elements are added to the PlayerXMLWriter
object, which store the names and scores of three players. The SaveXMLFile()
method is called and a debug print()
message is displayed.
The PlayerXMLWriter
class works as follows: when a new object is created, the provided file path string is stored in a private variable; at the same time, a check is made to see whether any file already exists. If an existing file is found, the content elements are removed; if no existing file is found, then a new root element, playerScoreList
, is created as the parent for child data nodes. The AddXMLElement()
method appends a new data node for the provided player name and score. The SaveXMLFile()
method saves the XML data structure as a text file for the stored file path string.
3.145.179.225