问题描述
关于我的另一个问题,我已经序列化数据然后反序列化它,但是当我将新数据写入反序列化的数组列表时,它不会将新数据添加到数组列表的末尾.相反,它会覆盖以前的列表数据.任何帮助都会很棒.到目前为止,这是我的代码:
In relation to my other question, I have serialized data and then deserialized it, but when I write new data to the deserialized arraylist, it does not add the new data to the end of the arraylist. Instead it is overwriting previous list data. Any help would be great. Here's my code so far:
{
ArrayList siteList = new ArrayList();
ArrayList copy = new ArrayList(siteList);
//if previous data exists, deserialize it
try
{
ArrayList deserializedArray = DeserializeArray();
foreach (var item in deserializedArray)
{
Console.WriteLine(item);
}
Console.WriteLine("------");
}
catch
{
Console.WriteLine("No previous data found");
}
siteList.Add("Test 3");
siteList.Add("Test 4");
//Display all current items in list
foreach (var item in siteList)
{
Console.WriteLine(item);
}
SerializeArray(siteList);
Console.Read();
}
public static void SerializeArray(ArrayList siteList)
{
XmlSerializer serializer = new XmlSerializer(typeof(ArrayList));
TextWriter textWriter = new StreamWriter("SiteList.xml");
serializer.Serialize(textWriter, siteList);
textWriter.Close();
}
static ArrayList DeserializeArray()
{
XmlSerializer deserializer = new XmlSerializer(typeof(ArrayList));
TextReader textReader = new StreamReader("SiteList.xml");
ArrayList siteList;
siteList = (ArrayList)deserializer.Deserialize(textReader);
textReader.Close();
return siteList;
}
}
}
推荐答案
您实际上从未将反序列化的数组列表中的数据分配给 siteList
,这是您稍后尝试更新的变量 - 直接分配:
You never actually assign the data from the deserialized arraylist to siteList
which is the variable that you try to update later - assign it directly:
ArrayList siteList = DeserializeArray();
并更新您的 DeserializeArray() 方法以处理不存在先前 XML 的情况:
and update your DeserializeArray() method to take care of the case that no prior XML exists:
static ArrayList DeserializeArray()
{
if(!File.Exists("SiteList.xml"))
return new ArrayList();
XmlSerializer deserializer = new XmlSerializer(typeof(ArrayList));
TextReader textReader = new StreamReader("SiteList.xml");
ArrayList siteList = (ArrayList)deserializer.Deserialize(textReader);
textReader.Close();
return siteList;
}
一般来说,用异常来控制流是一个坏主意,尤其是在这种情况下,您只能检查文件是否存在.
In general it is a bad idea to control flow with exceptions, especially in this case when you can just check whether the file exists or not.
最终的方法看起来像这样(去除了一些绒毛):
The final method would look something like this then (some fluff removed):
static void Main(string[] args)
{
ArrayList siteList = DeserializeArray();
siteList.Add("Test 3");
siteList.Add("Test 4");
foreach (var item in siteList)
{
Console.WriteLine(item);
}
SerializeArray(siteList);
Console.Read();
}
这篇关于反序列化但不添加到以前的 xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!