How do you deserialize XML data to a List that was serialized from a List?



I've serialized a bunch of records from a list to an XML file with the following code. This works very well, and I have a really nice XML file that stores my data when I close my program.


How do I now read that data back into my list when the program opens? I can't seem to figure out how to cycle through the records in the file and store them in my list of records.



private void WriteXML()
{
try
{
System.Xml.Serialization.XmlSerializer XMLwriter = new System.Xml.Serialization.XmlSerializer(typeof(callsignRecord));

System.IO.StreamWriter XMLfile = new System.IO.StreamWriter("Known Callsigns.xml");
foreach (callsignRecord callsign in Callsigns)
{
XMLwriter.Serialize(XMLfile, callsign);
}
XMLfile.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}


Below is as far as I got:



private void ReadXML()
{
try
{
System.Xml.Serialization.XmlSerializer XMLreader = new System.Xml.Serialization.XmlSerializer(typeof(callsignRecord));

System.IO.StreamReader XMLfile = new System.IO.StreamReader("Known Callsigns.xml");
while(!XMLfile.EndOfStream)
{
// Okay, great I can Deseralize the file, but how do the records go from the file to the List with this?
XMLreader.Deserialize(XMLfile);
}
XMLfile.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}


For reference, the data stored in the XML file came from a list with the following format:



public class callsignRecord
{
public string User { get; set; }
public List<AliasRecord> AliasRecords;
}

public class AliasRecord
{
public string Alias { get; set; }
public string Number { get; set; }
}


I also tried serializing the whole list as an object instead of doing it record by record, but that didn't work to well either.



private void WriteXML()
{
try
{
var XMLwriter = new XmlSerializer(typeof(List<callsignRecord>));

System.IO.StreamWriter XMLfile = new System.IO.StreamWriter("Known Callsigns.xml");
XMLwriter.Serialize(XMLfile, Callsigns);
XMLfile.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}

private void ReadXML()
{
System.IO.StreamReader XMLfile;
try
{
var XMLreader = new XmlSerializer(typeof(List<callsignRecord>));

XMLfile = new System.IO.StreamReader("Known Callsigns.xml");
Callsigns = (List<callsignRecord>)XMLreader.Deserialize(XMLfile);
XMLfile.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
//XMLfile.Close();
}
}

No comments:

Post a Comment