Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify one property is attribute of another In C# XML serialization?

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>
like image 737
Steve Crane Avatar asked Oct 11 '11 07:10

Steve Crane


1 Answers

If you are using XmlSerializer with default (non-IXmlSerializable) serialization, then indeed: this cannot be achieved without adding an extra class that is the AlertOne, with an attribute and a [XmlText] value.

If you implement IXmlSerializable it 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:

public class Alerts
{
    [XmlElement("AlertOne")]
    public Alert AlertOne { get; set; }
}
public class Alert
{
    [XmlText]
    public int Parameter { get; set; }
    [XmlAttribute("Enabled")]
    public bool Enabled { get; set; }
}

You could of course add a few [XmlIgnore] pass-thru members that talk to the inner instance.

like image 112
Marc Gravell Avatar answered Oct 16 '22 16:10

Marc Gravell