我正在使用XmlSerializer,并在一个类中拥有以下属性
public string Data { get; set; }
我需要确切按照这样的方式输出
<Data />
我应该如何达到这个目的?
我正在使用XmlSerializer,并在一个类中拥有以下属性
public string Data { get; set; }
我需要确切按照这样的方式输出
<Data />
我应该如何达到这个目的?
最近我在做这个,有一种替代方法,看起来更简单些。你只需要将属性的值初始化为空字符串,然后它就会创建一个空标签,正如你所需;
Data = string.Empty;
解决方法是创建一个PropertyNameSpecified
属性,序列化器使用该属性来确定是否对该属性进行序列化。例如:
public string Data { get; set; }
[XmlIgnore]
public bool DataSpecified
{
get { return !String.IsNullOrEmpty(Data); }
set { return; } //The serializer requires a setter
}
尝试使用public bool ShouldSerialize_PropertyName_(){},并在其中设置默认值。
public bool ShouldSerializeData()
{
Data = Data ?? "";
return true;
}
这个为什么能够起作用的描述可以在MSDN上找到。
[XmlElement(IsNullable = true)]
public string Data
{
get { return string.IsNullOrEmpty(this.data) ? string.Empty : this.data; }
set
{
if (this.data != value)
{
this.data = value;
}
}
}
private string data;
因此,您将不会遇到以下问题:
<Data xsi:nil="true" />
在渲染时会得到以下结果:
<Data />
[XmlElement(IsNullable=true)]
。这将强制XML序列化程序添加元素,即使它为空。 /// <summary>
/// The schedule days.
/// </summary>
public class ScheduleDays:GlobalSerializableBase
{
/// <summary>
/// Gets or sets the Monday backing variable.
/// </summary>
[ReadOnly(true)]
[XmlElement("Monday")]
public String MondayString
{
get { return _MondayString; }
set { _MondayString = value; }
}
private String _MondayString = null;
/// <summary>
/// Gets or sets whether the schedule runs on Monday.
/// </summary>
[XmlIgnore]
public bool Monday
{
get { return MondayString != null ; }
set { MondayString = value ? String.Empty : null; }
}
}
}
<Data />
的形式出现在 XML 中,且不带 xsi:nil="true" 属性。 - East of Nowhere