views:

28

answers:

1

I have two classes, shown below:

[Serializable]
[XmlInclude(typeof(SomeDerived))]
public class SomeBase
{
    public string SomeProperty { get; set; }
}

public class SomeDerived : SomeBase
{
    [XmlIgnore]
    public new string SomeProperty { get; set; }
}

When I serialize and instance of SomeDerived I don't expect to see a value for SomeProperty. However, I do. I've tried other approaches such as having SomeProperty declared as virtual in SomeBase and overriding it in SomeDerived. Still I see it in a serialized instance of SomeDerived.

Can anyone explain what is going on with the XmlIgnoreAttribute?

For completeness, my deserialization code is below

class Program
{
    static void Main(string[] args)
    {
        SomeDerived someDerived = new SomeDerived { SomeProperty = "foo" };

        XmlSerializer ser = new XmlSerializer(typeof(SomeBase));

        MemoryStream memStream = new MemoryStream();
        XmlTextWriter xmlWriter = new XmlTextWriter(memStream, Encoding.Default);
        ser.Serialize(memStream, someDerived);

        xmlWriter.Close();
        memStream.Close();
        string xml = Encoding.Default.GetString(memStream.GetBuffer());

        Console.WriteLine(xml);
        Console.ReadLine();
    }
}

Edit

I get the same behaviour if I change the serializer declaration to new XmlSerializer(typeof(SomeDerived)).

+1  A: 

Try this out. It uses the override on the XmlSerializer constructor to pass in some serialization overrides:

SomeDerived someDerived = new SomeDerived { SomeProperty = "foo" };

// Create the XmlAttributeOverrides and XmlAttributes objects.
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();

/* Use the XmlIgnore to instruct the XmlSerializer to ignore
    the GroupName instead. */
attrs = new XmlAttributes();
attrs.XmlIgnore = true;
overrides.Add(typeof(SomeBase), "SomeProperty", attrs);

XmlSerializer ser = new XmlSerializer(typeof(SomeBase), overrides);

MemoryStream memStream = new MemoryStream();
XmlTextWriter xmlWriter = new XmlTextWriter(memStream, Encoding.Default);
ser.Serialize(memStream, someDerived);

xmlWriter.Close();
memStream.Close();
string xml = Encoding.Default.GetString(memStream.GetBuffer());
Wallace Breza
@Richard Ev - I've updated my answer, take a look.
Wallace Breza
OK, that approach works for this specific scenario. However, is there a more generic approach that would also work?
Richard Ev
@Richard Ev - I'm not sure why the `XmlIgnore` attribute isn't working out of the box. I think its due to the fact that you hiding the property with `new`. I also attempted the same by changing `SomeProperty` to virtual and overriding in the derived class. It smells like a bug to me that the attributes aren't working for overridden members.
Wallace Breza