Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xml-attributes in interfaces and abstract classes

I found something that confused me today:

1. If I have this:

public interface INamed
{
    [XmlAttribute]
    string Name { get; set; }
}

public class Named : INamed
{
    public string Name { get; set; }
}

It gives the following output (Name property serialized as element):

<Named>
  <Name>Johan</Name>
</Named>

2. If I have this:

public abstract class NamedBase
{
    [XmlAttribute]
    public abstract string Name { get; set; }
}

public class NamedDerived : NamedBase
{
    public override string Name { get; set; }
}

The XmlSerializer throws System.InvalidOperationException

Member 'NamedDerived.Name' hides inherited member 'NamedBase.Name', but has different custom attributes.

The code I used for serialization:

[TestFixture] 
public class XmlAttributeTest
{
    [Test]
    public void SerializeTest()
    {
        var named = new NamedDerived {Name = "Johan"};
        var xmlSerializer = new XmlSerializer(named.GetType());
        var stringBuilder = new StringBuilder();
        using (var stringWriter = new StringWriter(stringBuilder))
        {
            xmlSerializer.Serialize(stringWriter, named);
        }
        Console.WriteLine(stringBuilder.ToString());
    }
}

My question is:

Am I doing it wrong and if so what is the correct way to use xml attributes in interfaces and abstract classes?

like image 769
Johan Larsson Avatar asked Nov 01 '12 17:11

Johan Larsson


1 Answers

Attributes are not inherited on overriden properties. You need to redeclare them. Also in your first example the behavior is not the "expected" one as you declared XmlAttribute at the interface level and yet the serialized xml contains the value as an element. So the attribute in the interface is ignored and only info taken from the actual class matters.

like image 78
Adrian Zanescu Avatar answered Sep 22 '22 00:09

Adrian Zanescu