Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 722
John Avatar asked Jun 02 '10 13:06

John


People also ask

How do I remove an empty XML tag?

You can to remove empty XML tags from messages for optimization. For example, an XML representation of an integration object might have unused integration components. You can use the siebel_ws_param:RemoveEmptyTags parameter to remove empty tags when making Web service calls.

How to ignore property in Xml serialization c#?

To override the default serialization of a field or property, create an XmlAttributes object, and set its XmlIgnore property to true . Add the object to an XmlAttributeOverrides object and specify the type of the object that contains the field or property to ignore, and the name of the field or property to ignore.


2 Answers

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);
    }
}
like image 170
Thomas Levesque Avatar answered Oct 14 '22 08:10

Thomas Levesque


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/

like image 43
Scoregraphic Avatar answered Oct 14 '22 07:10

Scoregraphic