我的类(class)
public MyClass
{
[DataMemberAttribute(EmitDefaultValue = true)]
public decimal? a { get; set; }
[DataMemberAttribute(EmitDefaultValue = true)]
public DateTime? b { get; set; }
[DataMemberAttribute(EmitDefaultValue = true)]
public int? c { get; set; }
[DataMemberAttribute(EmitDefaultValue = true)]
public bool? d { get; set; }
}
Decimal、DateTime 和 int 可以为空。所以我有:
<MyClass ...>
<a>3</a>
<b i:nil="true"/>
<c i:nil="true"/>
<d i:nil="true"/>
</MyClass>
当 a、b、c 为 null 时,我想得到这个:
<MyClass ...>
<a>3</a>
<b/>
<c/>
<d/>
</MyClass>
最佳答案
您只需要为您想要的每个元素创建如下属性:
public MyClass
{
[System.Xml.Serialization.XmlElement("b",IsNullable = false)]
public object b
{
get
{
return b;
}
set
{
if (value == null)
{
b = null;
}
else if (value is DateTime || value is DateTime?)
{
b = (DateTime)value;
}
else
{
b = DateTime.Parse(value.ToString());
}
}
}
//public object b ....
}
关于c# - XmlSerializer 如何排除空值但保留标记? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30209586/