XmlSerializer 如何排除空值但保留标记? C#

XmlSerializer How to exclude null value but keep the tag ? c#

我的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 可以为 null。所以我有:

<MyClass ...>
    <a>3</a>
    <b i:nil="true"/>
    <c i:nil="true"/>
    <d i:nil="true"/>
</MyClass>

当 a、b、c 为空时,我想得到这个:

<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 ....

}

我终于做到了:

XmlSerializer.SerializeToWriter(data, strw);
XDocument xdoc = XDocument.Load("myxmlfile.xml");

foreach (var attribute in xdoc.Descendants())
{
     if (attribute.FirstAttribute != null && attribute.FirstAttribute.ToString().Contains("i:nil"))
            attribute.FirstAttribute.Remove();
}
xdoc.Save("myxmlfile.xml");

而在我的 class 我有

[DataMemberAttribute(EmitDefaultValue = true)]

所以当它为空时,它生成 'i:nil="true"',然后我只需要删除它。