Creating XML text files – saving XML directly to text files with XMLDocument.Save()

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.

How to do it...

To save XML data to text files directly, perform the following steps:

  1. Create a new C# script named 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);
        }
    }
  2. Add the following C# script to Main Camera:
    // 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);
        }
    }
  3. Build and run your (Windows, Mac, or Linux) standalone executable. You'll need to save the current scene and then add this to the list of scenes in the build.
  4. You should now find a new text file named playerData.xml in the Data folder of your project's standalone files, containing the XML data for the three players:
    How to do it...
  5. The contents of the playerData.xml file should be the XML player list data:
    How to do it...

How it works...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.142.85