C# XML 序列化 XML 没有标签的元素
C# XML Serialization XMLElement without tag
我有以下 class:
[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>
第二个 xml 元素的含义,它不应该有自己的标签。这可能吗?谢谢。
用 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; }
}
我有以下 class:
[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>
第二个 xml 元素的含义,它不应该有自己的标签。这可能吗?谢谢。
用 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; }
}