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

狂风中的少年 提交于 2019-12-18 06:18:05

问题


I have an object like this,

public class UserObj
{
    public string First {get; set;}
    public string Last  {get; set;}
    public addr Address {get; set;}

}

public class addr
{
    public street {get; set;}
    public town   {get; set;}
}

Now when I use XmlSerializer on it and street and town are empty I get this in the XML output,

 <Address />

Is there a way not to output this empty tag?

Thanks


回答1:


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/




回答2:


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);
    }
}



回答3:


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;}

}



回答4:


I think assigning null value to address field should work.



来源:https://stackoverflow.com/questions/2958151/how-do-i-stop-an-empty-tag-from-being-emitted-by-xmlserializer

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