6

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>
1
  • For info, personally I think that splitting the parameter/enabled into their own type makes sense purely from a design perspective (forgetting about xml) - they are clearly 2 properties of a item "AlertOne", which is an alert. Presumably other alerts have similar features? Commented Oct 11, 2011 at 7:40

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is pretty much what I thought.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.