【发布时间】:2011-05-02 12:21:18
【问题描述】:
假设我有一个customer 类,我会将这个类序列化为xml。序列化后,我们将获得 xml 数据,但我需要 customer 类的一些属性根据少数条件按需序列化。有可能吗?
我不知道该怎么做。谁能帮我解决这个问题?
【问题讨论】:
标签: c# xml-serialization
假设我有一个customer 类,我会将这个类序列化为xml。序列化后,我们将获得 xml 数据,但我需要 customer 类的一些属性根据少数条件按需序列化。有可能吗?
我不知道该怎么做。谁能帮我解决这个问题?
【问题讨论】:
标签: c# xml-serialization
您可以添加一个或多个ShouldSerializeXXXXXX() 方法,其中XXXXXX 是您要根据条件序列化的每个属性的名称。
例如:
public class Customer
{
[DefaultValue(null)]
public string SomeInfo { get; set; }
[DefaultValue(null)]
public string SomeOtherInfo { get; set; }
#region Serialization conditions
// should SomeInfo be serialized?
public bool ShouldSerializeSomeInfo()
{
return SomeInfo != null; // serialize if not null
}
// should SomeOtherInfo be serialized?
public bool ShouldSerializeSomeOtherInfo()
{
return SomeOtherInfo != null; // serialize if not null
}
#endregion
}
【讨论】:
您可以使用 XmlAttributeOverrides 并覆盖您的属性的 XmlIgnore 属性。
(XmlIgnoremsdn 页面中有示例)
【讨论】: