XML序列化 - 渲染空元素

24

我正在使用XmlSerializer,并在一个类中拥有以下属性

public string Data { get; set; }

我需要确切按照这样的方式输出

<Data />

我应该如何达到这个目的?

6个回答

34

最近我在做这个,有一种替代方法,看起来更简单些。你只需要将属性的值初始化为空字符串,然后它就会创建一个空标签,正如你所需;

Data = string.Empty;

1
对于字符串,这个方法非常有效!如果 Data 没有被赋值,它将以 <Data /> 的形式出现在 XML 中,且不带 xsi:nil="true" 属性。 - East of Nowhere

10

解决方法是创建一个PropertyNameSpecified属性,序列化器使用该属性来确定是否对该属性进行序列化。例如:

public string Data { get; set; }

[XmlIgnore]
public bool DataSpecified 
{ 
   get { return !String.IsNullOrEmpty(Data); }
   set { return; } //The serializer requires a setter
}

3

尝试使用public bool ShouldSerialize_PropertyName_(){},并在其中设置默认值。

public bool ShouldSerializeData()
{
   Data = Data ?? "";
   return true;
}

这个为什么能够起作用的描述可以在MSDN上找到。


2
我改正了。添加了相关文档的链接,以便他人不再犯同样的错误。 - BradleyDotNET

2
您可以尝试为该成员添加XMLElementAttribute,例如[XmlElement(IsNullable=true)],并在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;

因此,您将不会遇到以下问题:

<Data xsi:nil="true" />

在渲染时会得到以下结果:

<Data />

1
你可以尝试在该成员上添加XMLElementAttribute,例如[XmlElement(IsNullable=true)]。这将强制XML序列化程序添加元素,即使它为空。

13
但这样不会使 <Data xsi:nil="true" /> 无效吗? - Jaimal Chohan

0
我们刚刚遇到了与微软组策略XML格式相关的问题,它以一种奇怪的方式存储每周日程运行的每一天作为空的XML元素。
我同意Jaimal Chohan的方法-您可以通过将支撑字符串变量设置为只读,然后根据用户可访问的布尔变量将其设置为null或空字符串来使其更友好地使用PropertyGrid。
    /// <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; }
        }


    }



}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接