How do I stop an empty tag from being emitted by XmlSerializer?

半城伤御伤魂 提交于 2019-11-29 10:38:22

You may implement IXmlSerializable and implement the serialization routine on your own. This way, you can avoid the element.

An example here: http://paltman.com/2006/jul/03/ixmlserializable-a-persistable-example/

You can implement a ShouldSerializeAddress method to decide whether or not the Address property should be serialized :

public bool ShouldSerializeAddress()
{
    return Address != null
        && !String.IsNullOrEmpty(Address.street)
        && !String.IsNullOrEmpty(Address.town);
}

If the method exists with this signature, the serializer will call it before serializing the property.

Alternatively, you can implement an AddressSpecified property which has the same role :

public bool AddressSpecified
{
    get
    {
        return Address != null
            && !String.IsNullOrEmpty(Address.street)
            && !String.IsNullOrEmpty(Address.town);
    }
}

You can eliminate the empty value by adding a DefaultValue attribute to the property. When the value of the property matches the default value, it isn't serialized. You set the default value to null, to eliminate the serialization. Here's an example:


using System.ComponentModel;
public class UserObj
{
    public string First {get; set;}
    public string Last  {get; set;}

    [DefaultValue(null)]
    public addr Address {get; set;}

}

I think assigning null value to address field should work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!