Reputation: 1922
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
Upvotes: 6
Views: 1492
Reputation: 5723
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;}
}
Upvotes: 1
Reputation: 292465
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);
}
}
Upvotes: 6
Reputation: 7200
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/
Upvotes: 2