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
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.
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.
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 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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With