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 (the Name property serialized as an 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; } } 

XmlSerializer throws a System.InvalidOperationException

Member 'NamedDerived.Name' hides the inherited element 'NamedBase.Name', but has different user 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:

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

+4
source share
2 answers

Attributes are not inherited when overriding properties. You need to update them. Also in your first example, the behavior is not "expected", since you declared XmlAttribute at the interface level, and yet serialized xml contains the value as an element. Thus, the attribute in the interface is ignored and only the information taken from the actual class matters.

+4
source

I think you need xmlignore your abstract class property

 public abstract class NamedBase { [XmlIgnore] public abstract string Name { get; set; } } public class NamedDerived : NamedBase { [XmlAttribute] public override string Name { get; set; } } 
+6
source

Source: https://habr.com/ru/post/1443490/


All Articles