Unity XML Confusion

I’ve been having trouble understanding how to write to an XML file in unity. I’ve tried looking at tutorials and examples on how to program it in C# from MSDN but all the examples have just confused me as none of them seem to work or I get lost in what I’m supposed to be doing. I’ve tried using XmlWriter:

void SavePlayer(string playerName)
    {
        using (XmlWriter writer = XmlWriter.Create(_saved_file.name + ".xml"))
        {

            writer.WriteStartDocument ();
            writer.WriteStartElement ("File");

            writer.WriteStartElement ("Player");

            writer.WriteElementString ("Name", playerName);
            writer.WriteElementString ("Level", "1");

            writer.WriteEndElement ();
            writer.WriteEndElement ();
            writer.WriteEndDocument ();
            writer.Close();
        }
    }

I’ve tried making the base nodes and attempting to save them to the file:

void SavePlayer(string playerName)
    {
        XmlDocument xmlDoc = new XmlDocument();
        XmlNode rootNode = xmlDoc.CreateElement("users");
        xmlDoc.AppendChild(rootNode);
       
        XmlNode userNode = xmlDoc.CreateElement("user");
        XmlAttribute attribute = xmlDoc.CreateAttribute("age");
        attribute.Value = "42";
        userNode.Attributes.Append(attribute);
        userNode.InnerText = "John Doe";
        rootNode.AppendChild(userNode);
       
        userNode = xmlDoc.CreateElement("user");
        attribute = xmlDoc.CreateAttribute("age");
        attribute.Value = "39";
        userNode.Attributes.Append(attribute);
        userNode.InnerText = "Jane Doe";
        rootNode.AppendChild(userNode);
       
        xmlDoc.Save(_saved_file.name + ".xml");

    }

Again these are examples that I found while trying to find a solution but have yet to find one that works. I have seen some documentation on XmlSerialization but I cannot understand it. Any help would be appreciated

You say they don’t work, but you haven’t showed us any errors or told us what is or isn’t happening. What specifically do you need help with?

Have a look into the xmlserializer

When I say it doesn’t work I mean it doesn’t write anything to the file, I run the code and go to check the file and the information that I wanted to be in the file isn’t there.

I’ve had a look at xmlserializer and I’m still a bit unsure about how it works, but I have to ask is it the only form of reading and writing from an xml document because I managed to find another example that works for reading but I don;t know how I can turn it into writing to the file (http://unitynoobs.blogspot.co.uk/2011/02/xml-loading-data-from-xml-file.html)

Have you tried creating the XmlWriter and saving it at the end of the function instead of saving it in the declaration?

I thought that’s what I’ve done with the first example, or is there something I’m missing, I tried to do a XmlDocument.Save but it didn’t like it

Where are you looking for the file? It should be throwing an exception if something went wrong. Seems weird there are no errors. Is this in the build or editor?

Here is some example code.

Click for code

using System;
using UnityEngine;
using System.Xml.Serialization;
using System.IO;

public class TestXMLSerialize : MonoBehaviour
{
    public string myName;
    public int myAge;

    string desktopFolder {get {return Environment.GetFolderPath(Environment.SpecialFolder.Desktop);}}
    string xmlFileName = "XMLTestSomeObject.xml";
    string path;

    void Awake()
    {
        path = Path.Combine(desktopFolder, xmlFileName);
        SaveToXML();
        LoadFromXML();
    }

    public void SaveToXML()
    {
        SomeObject someObject = new SomeObject() {name = myName, age = myAge};

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(SomeObject));
        TextWriter textWriter = new StreamWriter(path);
        xmlSerializer.Serialize(textWriter, someObject);
        textWriter.Close();

        Debug.Log("Xml Saved!");
    }

    public SomeObject LoadFromXML()
    {
        if(Directory.Exists(path) || File.Exists(path))
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(SomeObject));
            TextReader textReader = new StreamReader(path);
            SomeObject someObject = (SomeObject)(xmlSerializer.Deserialize(textReader));
            textReader.Close();

            Debug.Log("Xml Loaded! - Name = " + someObject.name + " and Age = " + someObject.age);
            return someObject;
        }

        Debug.Log("Xml file not found");
        return new SomeObject();
    }
}

public class SomeObject
{
    public string name;
    public int age;
}

The video I posted in a previous post does it differently. I am not sure if there is any drawbacks with how I did it here.

Put this on a gameobject, enter the info and press play.
The xml file will be saved (serialized) on your desktop (if you have any xml file named XMLTestSomeObject it will be overwritten).
The output is this

It will also debug.log what it read from the xml file itself (deserialized).

Hopefully this can help you out. There can be more to xmlserialization such as attributes and what not.

I tried to use the example for the xml serializer but it didn’t work, as in it printed “XML saved” but when I go to check the file there isn’t anything in the file, next I want to ask is this only limited to creating a new file from nothing and making it overwrite every time I go to save or can I make it so that I can append the file instead?

void SavePlayer(string playerName)
    {
        Player _player = new Player (playerName, 20, 5, 4, 3);

        string path = _saved_file.name + ".xml";
        print (path);

        XmlSerializer xmlSerializer = new XmlSerializer (typeof(Player));
        TextWriter textWriter = new StreamWriter (path);
        xmlSerializer.Serialize (textWriter, _player);
        textWriter.Close ();

        print ("XML Saved");
    }

also Player is a public class so that’s not the problem and _saved_file is a textasset

Did my example, unaltered, work?
Can you post your player class? Are your variables public?

Well to be honest I didn’t try your code unaltered but is that the same way in which I should do it in the context of my project and yes all the variables of the class have public properties and the class itself is public, I don’t know what I’m missing, unless the class that I’m serializing has to be in the same file as the main class

first confirm that my code unaltered worked, then I guess I would need to see your class or something. I am not really an expert on this subject. That code I gave is pretty much all Ive got =)