为了方便将对象保存在XML文件中,以备以后直接拿来使用,因此使用序列化对象的方法,将对象转换为XML文件中的内容,使用反序列化,将XML文件的内容反序列化为对象。
序列化与所需准备的对象:
[Serializable]
public class Book
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlAttribute("Author")]
public string Author { get; set; }
[XmlAttribute("About")]
private ObservableCollection<Bc> _bContent = new ObservableCollection<Bc>();
public ObservableCollection<Bc> BContent
{
get { return _bContent; }
set { _bContent = value; }
}
}
[Serializable]
public class Bc
{
[XmlAttribute("First")]
public string First { get; set; }
[XmlAttribute("Content")]
public string Content { get; set; }
}
序列化与反序列化的模板方法:
public static class XmlSerilaize
{
//序列化
public static void XmlSerialize<T>(this T obj, string path)where T :class
{
XmlSerializer xmls = new XmlSerializer(obj.GetType());
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
{
xmls.Serialize(fs, obj);
}
}
//反序列化
public static T XmlDeserialize<T>(this T obj,string path)where T :class
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
XmlSerializer xmldes = new XmlSerializer(obj.GetType());
return xmldes.Deserialize(fs) as T;
}
}
}
序列化与反序列化方法的调用:
static void Main()
{
string path = "../../xml/Test.xml";
// MyCollection.LoadFile(path);
MyCollection.DLoadFile(path);
foreach (var item in MyCollection.Books)
{
Console.WriteLine(string.Format($"{item.Name}{item.Author}"));
foreach (var item1 in item.BContent )
{
Console.WriteLine(string.Format($"{item1.First}{item1.Content}"));
}
};
Console.ReadKey ();
}
}
public static class MyCollection
{
private static ObservableCollection<Book> books = new ObservableCollection<Book>();
public static ObservableCollection<Book> Books
{
get { return books; }
set { books = value; }
}
public static void LoadFile(string filePath)
{
Book bk = new Book();
bk.Name = "Harry Port";
bk.Author = "J.K.LoLin";
Bc bc = new Bc();
bc.First = "第一章";
bc.Content = "内容";
bk.BContent.Add(bc);
Book bk1 = new Book();
bk1.Name = "Harry Porttttt";
bk.Author = "J.K.LoLin";
Bc bc1 = new Bc();
bc1.First = "第二章";
bc1.Content = "内容";
bk1.BContent.Add(bc1);
books.Add(bk1);
books.Add(bk);
books.XmlSerialize(filePath);
}
public static void DLoadFile(string filePath)
{
Books = Books.XmlDeserialize(filePath);
}
}