简体   繁体   中英

Export list of list to XML and vice-versa

I'm trying to implement an "Open/Save" function for my Visual C# program. The object I need to save is a list of list. More specifically it's a List<List<Components>> , where Components is my custom class. I managed to export it and I read my variables with an XML reader, but when I imported it back into program, I got wrong variables. For example, the list capacity before exporting it, was 2. After importing it, it became 4. Any help?
If you can suggest another way of "Open/Save" function, feel free. I just need to store and restore a list of lists of custom class into a file.

public void open_click(object send, EventArgs e)
        {
            XmlSerializer xml = new XmlSerializer(typeof(List<List<Components>>));
            OpenFileDialog oDialog = new OpenFileDialog();

            oDialog.Filter = "XML|*.xml";

            if (oDialog.ShowDialog() == DialogResult.OK)
            {
                Variables.compBuffer = new List<List<Components>>();
                using (FileStream s = File.OpenRead(oDialog.FileName))
                using (StreamReader sw = new StreamReader(s))
                {
                    Variables.compBuffer = (List<List<Components>>)xml.Deserialize(s);
                }
            }
        }    

//

public void saveAs_click(object send, EventArgs e)
{
    XmlSerializer xml = new XmlSerializer(typeof(List<List<Components>>));
    SaveFileDialog sDialog = new SaveFileDialog();

    sDialog.FileName = "myLadder";
    sDialog.Filter = "XML|*.xml";
    sDialog.OverwritePrompt = true;

    if (sDialog.ShowDialog() == DialogResult.OK)
    {
        using (FileStream s = File.OpenWrite(sDialog.FileName))
        using (StreamWriter sw = new StreamWriter(s))
        {
            xml.Serialize(s, Variables.compBuffer);
        }
    }
}    

//

    public class Components
    {
        //Private variables
        private string _type = "empty";
        private string _name = "";
        private int _time = 0;    //If it's a "timer" (in ms)
        private int _index = -1;
        private string _comment = "";
        private bool _output = false;

        public Components() { }

        public string Type
        {
            get { return this._type; }
            set { this._type = value; }
        }
        public string Name
        {
            get { return this._name; }
            set { this._name = value; }
        }
        public int Time
        {
            get { return this._time; }
            set { this._time = value; }
        }
        public int Index
        {
            get { return this._index; }
            set { this._index = value; }
        }
        public string Comment
        {
            get { return this._comment; }
            set { this._comment = value; }
        }
        public bool Output
        {
            get { return this._output; }
            set { this._output = value; }
        }

        public void reset()
        {
            _type = "empty";
            _name = "";
            _time = 0;               //If it's a "timer" (in ms)
            _index = -1;
            _comment = "";
            _output = false;
        }
    }
}

Since you not looking into xml specific solution, I would just serialize it as a binary representation into a file, and restore it back:

    using System.IO;

    [Serializable]    
    public class Components
    {
       ...
    }

    var components = new List<Components>();
    string pathToFile = @"c:\dev\components.bin";

    SerializeFile(pathToFile, components);
    var fetchComponents = DeserializeFile(pathToFile);

    private void SerializeFile(string file, IList<Components> data)
    {
        using (Stream stream = File.Open(file, FileMode.Create))
        {
           var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
           formatter.Serialize(stream, data);
        }
    }

    private IList<Components> DeserializeFile(string file)
    {
        using (Stream stream = File.Open(file, FileMode.Create))
        {
            var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            return (List<Components>)formatter.Deserialize(stream);
        }
    }

The drawback with this solution is you cannot look into the file and browse the data. Further improvements would be to use generics so you can serialize/deserialize any type of data.

Don't forget to mark your class you would like to save with the attribute [Serializable]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM