Пример сериализации объекта в XML файл

C Sharp > Пример сериализации объекта в XML файл
09.02.2018 16:04:51


Наиболее часто встречающиеся слова в статье:

[serializer] [SoapFormatter] [Dispose] [Serializable] [TestBooks] [GetEnumerator] [Program] [Serialize] [//Stream] [OpenRead]


Статья:

  class Program
    {
        static void Main(string[] args)
        {
            Books books = new Books();
 
            Stream stream = File.Create("books.txt");
            SoapFormatter serializer = new SoapFormatter();
            serializer.Serialize(stream, books);
            stream.Dispose();
 
            //Stream stream = File.OpenRead("books.txt");
            //SoapFormatter serializer = new SoapFormatter();
            //Books bs = (Books)serializer.Deserialize(stream);
            //stream.Dispose();
 
            //foreach (Book b in bs) Console.WriteLine(b);
 
        }
    }
 
 [Serializable]
    class Books : IEnumerable
    {
        Book[] books;
        public Books() { books = Book.TestBooks(); }
 
        public IEnumerator GetEnumerator()
        {
            return books.GetEnumerator();
        }
    } 
 
    [Serializable]
    class Book
    {
        public int    Id     { get; set; }
        public double Price  { get; set; }
        public string Title  { get; set; }
        public string Author { get; set; }
 
        public override string ToString()
        {
            return "id="+Id+" price="+Price+"$  "+Author+" : "+Title;
        }
 
        public static Book[] TestBooks()
        {
            Book[] data = new Book[] 
            {
                new Book() {Id=1, Price=32, Author="Seemann", Title="Dependency Injection in .NET" },
                new Book() {Id=2, Price=42, Author="Richter", Title="CLR via C#" },
                new Book() {Id=3, Price=21, Author="Munro", Title="ASP.NET MVC 5" },
                new Book() {Id=5, Price=30, Author="Esposito", Title="Architecting Applications for the Enterprise" },
                new Book() {Id=6, Price=23, Author="Watson", Title="Writing High-Performance .NET Code" },
                new Book() {Id=7, Price=37, Author="Sharp", Title="Microsoft Visual C# 2013" },
                new Book() {Id=9, Price=11, Author="Stubblebine", Title="Regular Expression" },
                new Book() {Id=10, Price=27, Author="Liberty", Title="Learning Visual Basic .Net" },
                new Book() {Id=11, Price=62, Author="Cwalina", Title="Framework Design Guidelines" },
                new Book() {Id=12, Price=55, Author="Blewett", Title="Pro Asynchronous Programming with .NET" },
                new Book() {Id=13, Price=47, Author="Nathan", Title="Windows Presentation Foundation Unleashed" },
            };
            return data;
        }
    }