2
[TestFixture]
public class XmlIgnoreWithNewModifierTest
{
    public class Parent
    {
        public int Name { get; set; }
    }

    public class Child : Parent
    {
        [XmlIgnore]
        public new int Name
        {
            get { throw new NotImplementedException(); }
        }
    }

    [Test]
    public void Test()
    {
        var serializer = new XmlSerializer(typeof(Child));
        var stream = new MemoryStream();

        // Throws
        serializer.Serialize(stream, new Child());
    }
}

The last line of code would throw InvalidOperationException with an inner NotImplementedException. Making Parent.Name virtual and Child.Name override doesn't help.

I wonder if it is possible to make XmlIgnore only work on Child.Name but not Parent.Name?

Chris Xue
  • 2,317
  • 1
  • 25
  • 21

1 Answers1

0

As mentioned in this answer : Excluding some properties during serialization without changing the original class

You should use :

XmlAttributes attributes = new XmlAttributes { XmlIgnore = true };
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof(Parent), "Name", attributes);

XmlSerializer serialize = new XmlSerializer(typeof(Child), overrides);
Community
  • 1
  • 1
Clavat
  • 107
  • 1
  • 8