During the serialization of c# classes into xml, I need to match a certain xml structure, but it would be for the best not to alter the class structure already present.
Is it possible to create a sort of grouping of a number of properties into their own xml element where they store their values as xml attributes?
An example c# code would be something like:
class SomeClass {
[XmlElement("Element1")]
[XmlAttribute("attribute1")]
int prop1;
[XmlElement("Element1")]
[XmlAttribute("attribute2")]
int prop2;
[XmlElement("Element2")]
[XmlAttribute("attribute1")]
int prop3;
[XmlElement("Element2")]
[XmlAttribute("attribute2")]
int prop4;
[XmlElement("Element2")]
[XmlAttribute("attribute3")]
int prop5;
[XmlElement("Element2")]
[XmlAttribute("attribute4")]
int prop6;
}
With an xml output of:
<SomeClass>
<Element1 Attribute1="value1" attribute2="value2"/>
<Element2 Attribute1="value3" attribute2="value4" attribute3="value5" attribute4="value6"/>
</SomeClass>
after serialization.
It would be amazing if the solution worked for deserialization as well.
If you really must avoid "altering the class structure", attributes are (in my opinion) not going to get the XML structure you would like and help you get readable, maintainable code.
The IXmlSerializable interface allows you to manually control serialization/deserialization of your class. When implementing this interface, you have full control to create whatever XML text you desire when your class is consumed by XmlSerializer.
Below is a compiling console app example for you to play with. It shows how to read and write custom nodes within your
SomeClass
XML, and putting your class properties into XML attributes on those nodes. Note I usednameof
to get an attribute name, but you could just as easily hard-code the XML attribute names to"Attribute1"
,"Attribute2"
if you wanted.As you will see, it's more cumbersome to write than using attributes. But it can be pretty straightforward once you get the hang of it. And it definitely doesn't change the class structure.
(If you like this, you should clean it up before actually deploying it - there's no error handling present, for example on
int.Parse
. It's just meant to illustrate the use ofIXmlSerializable
without changing the class structure at all.)