c# XML序列化XMLElement不带标签

本文关键字:标签 XMLElement XML 序列化 | 更新日期: 2023-09-27 18:06:51

我有以下类:

[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的意思是,它不应该有自己的标记。这可能吗?谢谢你。

c# XML序列化XMLElement不带标签

用XmlText代替XmlElement装饰CustomerAge

您还必须将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; }
}