简体   繁体   中英

c# xml serialization grouping elements in subnodes

I would like to serialize some class fields into a group (a 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 instance street and city into a subelement), without making an extra subclass holding this two properties.

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

You can serialize 'by hand', ie write to an XDocument (or even an XmlWriter).

That gives you total control over the format. Using a serializer means you give up (most of) that control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM