How to serialize abstract classes with a large number of subclasses?

48 Views Asked by At

I am trying to serialize a class with a field containing another class, but the field name appears in the XML.

I have the following classes:

public class CustomExpression
{
    [XmlAttribute] public string callFormat;
    [XmlAttribute] public string format;
    [XmlAttribute] public string name;
    [XmlAttribute] public string style;

    public VzExpression child;

    
    /* constructor and methods */
}

[XmlInclude(typeof(BinaryOp)) /* other subclasses */]
public abstract class VzExpression {}

public class BinaryOp : VzExpression
{
    public VzExpression left;
    public VzExpression right;    

    /* constructor and methods */
}

/* And some more subclasses */

Which currently serializes as:

<CustomExpression callFormat="" format="" name="" style="">
  <child xsi:type="BinaryOp" ...>
    <left ... />
    <right ... />
  </child>
</CustomExpression>

What I instead want is (replace VzExpression with concrete type):

<CustomExpression callFormat="" format="" name="" style="">
  <BinaryOp ...>
    <VzExpression ... />
    <VzExpression ... />
  </BinaryOp>
</CustomExpression>

How should I achieve this?

One solution I attempted, as suggested by @dbc, was adding the [XmlElement("BinaryOp", typeof(BinaryOp))] attribute to the field for every subclass. However, the number of subclasses is large (~ 10). Is there a way to do this without having to apply 10 attributes every time I use VzExpression?

0

There are 0 best solutions below