Question

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)).

Was it helpful?

Solution

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());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top