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?
source share