Control Serialization of Derived Classes : Serialization « XML « C# / C Sharp






Control Serialization of Derived Classes

 
using System;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;

using System.Xml.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Xml.XPath;
using System.IO;
public class Orders
{
    public Book[] Books;
}

public class Book
{
    public string ISBN;
}

public class ExpandedBook : Book
{
    public bool NewEdition;
}

public class Run
{
    public static void Main(){}

    public void SerializeObject(string filename)
    {
        XmlAttributes attrs = new XmlAttributes();
        XmlElementAttribute attr = new XmlElementAttribute();
        attr.ElementName = "NewBook";
        attr.Type = typeof(ExpandedBook);
        attrs.XmlElements.Add(attr);
        XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
        attrOverrides.Add(typeof(Orders), "Books", attrs);
        XmlSerializer s = new XmlSerializer(typeof(Orders), attrOverrides);
        TextWriter writer = new StreamWriter(filename);
        Orders myOrders = new Orders();
        ExpandedBook b = new ExpandedBook();
        b.ISBN = "123456789";
        b.NewEdition = true;
        myOrders.Books = new ExpandedBook[] { b };
        s.Serialize(writer, myOrders);
        writer.Close();
    }

    public void DeserializeObject(string filename)
    {
        XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
        XmlAttributes attrs = new XmlAttributes();
        XmlElementAttribute attr = new XmlElementAttribute();
        attr.ElementName = "NewBook";
        attr.Type = typeof(ExpandedBook);
        attrs.XmlElements.Add(attr);
        attrOverrides.Add(typeof(Orders), "Books", attrs);
        XmlSerializer s = new XmlSerializer(typeof(Orders), attrOverrides);
        FileStream fs = new FileStream(filename, FileMode.Open);
        Orders myOrders = (Orders)s.Deserialize(fs);
        Console.WriteLine("ExpandedBook:");
        ExpandedBook expanded;
        foreach (Book b in myOrders.Books)
        {
            expanded = (ExpandedBook)b;
            Console.WriteLine(expanded.ISBN + "\n" + expanded.NewEdition);
        }
    }
}

   
  








Related examples in the same category