Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring properties on derived classes when using .NET's XmlSerializer

I have a base class with a virtual property and a derived type that overrides the virtual property. The type can be serialized to XML. What I am trying to do is NOT to persist the List of items property when the object is of the derived type. To acheive this the derived class decorates the overridden property with the [XmlIgnore] attribute. The virtual property in the base class does NOT apply XmlIgnore attribute. For some reason the List of items get serialized every even when the object is of the derived type (DynamicCart).

When I apply XmlIgnore attribute to the virtual property in the base class the list does not get serialized to file.

public class ShoppingCart
{  
   public virtual List<items> Items{get; set;}

   //and other properties 

   public void SerializeToXML (string filePath)
   {
     var xmlSerializer = new XmlSerializer(this.GetType());
     textWriter = new System.IO.StreamWriter(filePath);
     xmlSerializer.Serialize(textWriter, this);
     textWriter.Flush();
     textWriter.Close();  
   }
}

//A cart that is populated by algo based on parameters supplied by user. I have no need to
//persist the actual items across sessions.
class DynamicCart: ShoppingCart
{
   [XmlIgnore]
   public override List<items>{get;set;}
   //and other properties 
}

class Shop
{
   ShoppingCart cart = new DynamicCart();
   PopulateCart(cart);
   cart.serializeToXML(<PATH TO FILE>);
}
like image 689
Ken Avatar asked Mar 11 '11 15:03

Ken


1 Answers

You can do this by adding a virtual ShouldSerialize*** method to the base class. For example:

[XmlInclude(typeof(Sub))]
public class Base
{
    public virtual string Prop { get; set; }

    public virtual bool ShouldSerializeProp() { return true; }
}

public class Sub : Base
{
    public override string Prop { get; set; }

    public override bool ShouldSerializeProp() { return false; }
}

internal class Program
{
    private static void Main()
    {
        var o = new Sub { Prop = "Value" };

        var baseSer = new XmlSerializer(typeof (Base));
        var subSer = new XmlSerializer(typeof (Sub));

        Console.Out.WriteLine("BASE:");
        baseSer.Serialize(Console.Out, o);
        Console.Out.WriteLine();

        Console.Out.WriteLine("SUB:");
        subSer.Serialize(Console.Out, o);
        Console.Out.WriteLine();

        Console.ReadLine();
    }
}

This produces (tidied slightly):

BASE:
<Base xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Sub">
  <Prop>Value</Prop>
</Base>

SUB:
<Sub />

The method must have include the exact name of the property to consider after ShouldInclude....

like image 182
Drew Noakes Avatar answered Nov 02 '22 01:11

Drew Noakes