Xml序列化 – 渲染空元素
我正在使用XmlSerializer并在类中具有以下属性
public string Data { get; set; }
我需要输出完全如此
我将如何实现这一目标?
我最近这样做,还有另一种方法,这似乎有点简单。 您只需要将属性的值初始化为空字符串,然后它将根据您的需要创建一个空标记;
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)]
等XMLElementAttribute添加到该成员。 这将强制XML Serializer添加元素,即使它是null。
您可以尝试将[XmlElement(IsNullable = true)]等XMLElementAttribute添加到该成员中,并在get / set属性中设置如下:
[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;
所以你不会:
你将在渲染上有这个: