没有标记的C#XML序列化XMLElement

时间:2016-09-14 07:16:35

标签: c# .net xml serialization xml-serialization

我有以下课程:

[Serializable]
public class SomeModel
{
    [XmlElement("CustomerName")]
    public string CustomerName { get; set; }

    [XmlElement("")]
    public int CustomerAge { get; set; }
}

其中(当填充一些测试数据时)和使用XmlSerializer.Serialize()进行序列化会产生以下XML:

<SomeModel>
  <CustomerName>John</CustomerName>
  <CustomerAge>55</CustomerAge>
</SomeModel>

我需要的是:

<SomeModel>
  <CustomerName>John</CustomerName>
   55
</SomeModel>

第二个xmlelement的含义,它不应该有自己的标记。这甚至可能吗?谢谢。

1 个答案:

答案 0 :(得分:4)

使用XmlText而不是CustomerAge装饰XmlElement

您还必须将CustomerAge的类型从int更改为string,如果您不想,则必须采取额外的属性进行序列化,如下所示:

public class SomeModel
{
    [XmlElement("CustomerName")]
    public string CustomerName { get; set; }

    [XmlText]
    public string CustomerAgeString { get { return CustomerAge.ToString(); } set { throw new NotSupportedException("Setting the CustomerAgeString property is not supported"); } }

    [XmlIgnore]
    public string CustomerAge { get; set; }
}