我使用以下代码将列表中的一堆记录序列化为XML文件。这非常有效,我有一个非常好的XML文件,可以在我关闭程序时存储我的数据。
如何在程序打开时将该数据读回我的列表?我似乎无法弄清楚如何在文件中循环记录并将它们存储在我的记录列表中。
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);
}
}
以下是我得到的:
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);
}
}
作为参考,存储在XML文件中的数据来自具有以下格式的列表:
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; }
}
我也尝试将整个列表序列化为一个对象而不是按记录进行记录,但这也不能很好地工作。
编辑:下面显示的代码确实有效。我尝试它失败的原因是我开始尝试反序列化按记录序列化的列表。显然,这两种方法不兼容,下面的代码是正确的方法。
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();
}
}
答案 0 :(得分:0)
你能试试吗
// Create an instance of CallsignRecordclass.
CallsignRecord serializeObject = new CallsignRecord();
// Create an instance of new TextReader.
TextReadertxtReader = new StreamReader(@”C:\Callsigns.xml”);
// Create and instance of XmlSerializer class.
XmlSerializerxmlSerializer = new XmlSerializer(typeof(CallsignRecord));
// Deserialize from the StreamReader.
serializeObject = (CallsignRecord)xmlSerializer.Deserialize(txtReader);
// Close the stream reader
txtReader.Close();
点击此处查看详情