c# 反序列化不起作用?
我有一个测试控制台应用程序,我试图在其中进行序列化和反序列化以将数据存储到 xml 文件中。序列化方法工作正常,但反序列化似乎不起作用。它不会产生任何错误,但不会从 .xml 文件加载我的数据。有人知道为什么吗?
class Program
{
static void Main(string[] args)
{
ArrayList siteList = new ArrayList();
DeserializeArray();
siteList.Add("Test 1");
siteList.Add("Test 2");
foreach (var item in siteList)
{
Console.WriteLine(item);
}
SerializeArray(siteList);
if (siteList.Contains("Test 2"))
{
Console.WriteLine("Test 2 exists!");
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;
}
}
}
I have a test console application, where I am trying to get serializaiton and deserialization to work to store data into an xml file. The serialize method works correctly, but the deserialization doesnt seem to be working. It does not produce any errors but it isnt loading my data from the .xml file. Anyone know why?
class Program
{
static void Main(string[] args)
{
ArrayList siteList = new ArrayList();
DeserializeArray();
siteList.Add("Test 1");
siteList.Add("Test 2");
foreach (var item in siteList)
{
Console.WriteLine(item);
}
SerializeArray(siteList);
if (siteList.Contains("Test 2"))
{
Console.WriteLine("Test 2 exists!");
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;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它工作正常(经过测试),您在
Main()
中的逻辑已关闭 - 您必须在反序列化之前先序列化,请尝试以下操作:It's working fine (tested), your logic in
Main()
is off - you have to serialize first before deserializing, try this:你的代码在这里工作得很好。我假设您拥有上次运行中的 SiteList.xml,因为您首先要反序列化。为了清楚起见,我添加了 Console.WriteLine 来转储反序列化的数据。
Your code works fine here. I'm assuming that you have your SiteList.xml from previous run, as you are deserializing first. I added Console.WriteLine to dump the deserialized data for clarity.