C # xml serialization grouping elements in subnodes

I would like to serialize some class fields into a group (subnode element). For instance:

[XmlRoot("person", Namespace = "", IsNullable = false)] public class Person { [XmlElement("male")] public bool Male { get; set; } [XmlElement("street")] public string Street { get; set; } [XmlElement("city")] public string City { get; set; } } 

This will create the following XML:

 <person> <male>true</male> <street>Some street</street> <city>City</city> </person> 

But I would like to group (for example, the street and the city into a sub-element) without creating an additional subclass that holds these two properties.

  <person> <male>true</male> <address> <street>Some street</street> <city>City</city> </address> </person> 
+4
source share
1 answer

You can serialize "manually", that is, write to XDocument (or even XmlWriter).

This gives you full control over the format. Using a serializer means that you are giving away (most of) this control.

+1
source

All Articles