开发者

c# xml serialization grouping elements in subnodes

开发者 https://www.devze.com 2023-04-12 14:23 出处:网络
I would like to serialize some class fields into a group (a subnode element). For instance: [XmlRoot(\"per开发者_开发百科son\", Namespace = \"\", IsNullable = false)]

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

[XmlRoot("per开发者_开发百科son", 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号