1

I am trying to write (and later read) a log in XML format. Log in my case is a stream of events, each having a corresponding class with XML serialization-compatible declaration. A trivial case is:

public abstract class Base {
    [XmlAttribute]
    public string Value { get; set; }
}
public class A: Base{}
public class B: Base{}

When I create XmlSerializer, I pass typeof(A), typeof(B) as the extraTypes parameter. That generates

<Base xsi:type="A" Value="42"/>
<Base xsi:type="B" Value="42"/>

I'd like to see

<A Value="42"/>
<B Value="42"/>

or at least

<A xsi:type="A" Value="42"/>

instead for readability.

Is it possible to do without manually generating serialization code and nesting?

I could create an instance of XmlSerializer per class, but I am not sure later I'd be able to deserialize its output.

NOTE: I am streaming, e.g. I am writing new instances of A or B as soon as they arrive into existing XmlWriter.

dbc
  • 104,963
  • 20
  • 228
  • 340
LOST
  • 2,956
  • 3
  • 25
  • 40
  • 1
    There's no way to get the "at least" format. You can get the `` format by creating an instance-specific serializer. Then later, to deserialize, you can construct an `XmlSerializer` for each possible type and call [`XmlSerializer.CanDeserialize(XmlReader)`](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.candeserialize.aspx) to test whether each serializer can be used, as shown in the answer to [How to deserialize XML if the return type could be an Error or Success object](https://stackoverflow.com/a/44248192/3744182). – dbc Jul 18 '18 at 22:25
  • @dbc , this approach works, but I wonder what is the performance penalty for deserialization. – LOST Jul 18 '18 at 23:41
  • You would have to construct multiple serializers, but this only causes one performance hit per session, see https://stackoverflow.com/q/23897145/3744182 for details. Then, since `XmlSerializer.CanDeserialize(XmlReader)` doesn't advance the reader, it must just be checking the root element name and namespace, which is quite performant. But beyond that see https://ericlippert.com/2012/12/17/performance-rant/ – dbc Jul 19 '18 at 00:32
  • @dbc , yeah, I switched to multiple serializers following the same logic :) – LOST Jul 19 '18 at 05:47
  • OK, so mark as a duplicate then? – dbc Jul 19 '18 at 06:05
  • 1
    @dbc , I guess it might be considered a duplicate then. Got a suitable answer anyway. – LOST Jul 19 '18 at 06:28

0 Answers0