I want to specify that one property in an XML serializable class is an attribute of another property in the class, not of the class itself. Is this possible without creating additional classes?
For example, if I have the following C# class
class Alerts
{
[XmlElement("AlertOne")]
public int AlertOneParameter { get; set; }
public bool IsAlertOneEnabled { get; set; }
}
how can I specify that IsAlertOneEnabled is an attribute of AlertOne so that the XML serializes to the following?
<Alerts>
<AlertOne Enabled="True">99</AlertOne>
</Alerts>
If you are using
XmlSerializerwith default (non-IXmlSerializable) serialization, then indeed: this cannot be achieved without adding an extra class that is theAlertOne, with an attribute and a[XmlText]value.If you implement
IXmlSerializableit should be possible, but that is not a nice interface to implement robustly (the deserialization, in particular, is hard; if it is write-only then this should be fine). Personally I’d recommend mapping to a DTO model with the aforementioned extra class.Other tools like LINQ-to-XML would make it pretty simple, of course, but work differently.
An example of a suitable DTO layout:
You could of course add a few
[XmlIgnore]pass-thru members that talk to the inner instance.