Deserializing but not adding to previous xml
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开发者_StackOverflow社区 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;
}
}
}
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();
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();
}
精彩评论