using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace XmlSerializeDemo
{
class Program
{
static void Main(string[] args)
{
List<Person> data = new List<Person>();
data.Add(new Person() { Name = "Kate", Age = 25 });
data.Add(new Person() {Name = "Tom", Age = 63 });
data.Add(new Person() { Name = "Michael", Age = 37 });
if (! SaveToXml(@"D:\test.xml", data))
{
Console.WriteLine("Save failed");
}
data.Clear();
data = ReadFromXml(@"D:\test.xml");
Console.ReadLine();
}
public static bool SaveToXml(string filePath,List<Person> data)
{
try
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
XmlSerializer serializer = new XmlSerializer(data.GetType());
FileStream fs = File.Open(filePath,FileMode.OpenOrCreate);
using (XmlWriter xmlWriter = XmlWriter.Create(fs, xmlWriterSettings))
{
serializer.Serialize(xmlWriter, data);
}
fs.Close();
return true;
}
catch (Exception)
{
return false;
}
}
public static List<Person> ReadFromXml(string filePath)
{
List<Person> data = new List<Person>();
try
{
XmlSerializer serializer = new XmlSerializer(data.GetType());
FileStream fs = File.Open(filePath, FileMode.Open);
data = (List<Person>)serializer.Deserialize(fs);
fs.Close();
return data;
}
catch
{
return data;
}
}
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
}