views:

65

answers:

4

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

+2  A: 

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/

Scoregraphic
+1  A: 

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);
    }
}
Thomas Levesque
A: 

Check out OXM which is a POCO approach to xml serialization by using a mapping API which gives you an exact control over the generated XML.

Delucia
A: 

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

}
Steve Wranovsky