Troubleshooting Reading XML

After following several tutorials I almost have my code working just the way I want, however when I call the load function it doesn’t appear to be correctly parsing the XML document (even though it acquires it) and returns a container of 0 items. Can anyone suggest how to amend my code?

Thanks!

The saving function works, but the load function returns a LeaderContainer of size 0 no matter what document it acquires.

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

[XmlRoot("leaders")]
public class LeaderContainer {

    [XmlArray("Leaders"), XmlArrayItem("Leader")]
    public List<MemoryManager.Leader> leaders = new List<MemoryManager.Leader>();


    public void Save(string path)
    {
        var serializer = new XmlSerializer(typeof(LeaderContainer));

        using (var stream = new FileStream(path, FileMode.Create))
        {
            serializer.Serialize(stream, this);
        }
    }


    public static LeaderContainer Load(string path)
    {
        Debug.Log("Loading " + path);
        TextAsset _xml = Resources.Load<TextAsset>(path);

        XmlSerializer serializer = new XmlSerializer(typeof(LeaderContainer));

        StringReader reader = new StringReader(_xml.text);

        LeaderContainer l = serializer.Deserialize(reader) as LeaderContainer;

        reader.Close();

        Debug.Log(l.rosterSize());

        return l;
    }

    public static LeaderContainer LoadFromText(string text)
    {
        var serializer = new XmlSerializer(typeof(LeaderContainer));
        return serializer.Deserialize(new StringReader(text)) as LeaderContainer;
    }

    public int rosterSize()
    {
        int size = 0;
        foreach (MemoryManager.Leader l in leaders)
        {
            size++;
        }
        return size;
    }

}

Your code works for me. How are you calling Save and Load? What does MemoryManager.Leader look like? Does the XML contain what you expect after Save is called?

-sam

Leader is an xml class and memory manager initializes a leader2 class that inherits monobehavior and iterates over the data in leader2 assigning it from the leader xml class.

The problem is before I even get to that it is reporting that my saved LeaderContainer (above), which is supposed to contain a list of leaders loaded from the xml, contains an empty list of leaders.

I’ll post some sample code asap.