简体   繁体   English

c#xml序列化分组子节点中的元素

[英]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: 这将创建以下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). 您可以“手动”序列化,即写入XDocument(甚至是XmlWriter)。

That gives you total control over the format. 这使您可以完全控制格式。 Using a serializer means you give up (most of) that control. 使用序列化程序意味着您放弃(大部分)该控件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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