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?
[XmlInclude(typeof(BinaryOp))apply[XmlElement(typeof(BinaryOp))]as shown in this answer by Marc Gravell to Using XmlSerializer to serialize derived classes. Does that answer your question?[XmlElement("BinaryOp", typeof(BinaryOp))topublic VzExpression child;works, see dotnetfiddle.net/bfBZso. Closing as a duplicate.XmlAttributeOverridesspecified, see e.g. Serialize a list of objects inheriting from class A to xml, so the names of the elements in the xml are B,C,D.