How to specify one property - is it an attribute of another in C # XML serialization?

I want to point out that one property in a serializable XML class is an attribute of another property in the class, not 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 indicate that IsAlertOneEnabled is an attribute of AlertOne, so that XML is serialized as follows?

 <Alerts> <AlertOne Enabled="True">99</AlertOne> </Alerts> 
+6
source share
1 answer

If you use the default serialization XmlSerializer (not IXmlSerializable ), then it’s valid: this cannot be achieved without adding an extra class, which is AlertOne , with the attribute and value [XmlText] .

If you implement IXmlSerializable , this should be possible, but it is not a very good interface for a reliable implementation (deserialization, in particular, is difficult if it is only for writing, then it should be good). Personally, I would recommend matching the DTO model with the above-mentioned extra class.

Other tools, such as LINQ-to-XML, will make it pretty simple, 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 members of the [XmlIgnore] pass-thru that talk to the internal instance.

+5
source

Source: https://habr.com/ru/post/899023/


All Articles