I am serializing a class, which has a boolean
parameter. I want to hide this parameter if it has value false
. Below is the class-
public class UserPreferences
{
[XmlAttributeAttribute("Name")]
public string Name;
[XmlAttributeAttribute("SaveOnClose")]
public bool SaveOnClose;
public UserPreferences() { }
public UserPreferences(string Name)
{
this.Name = Name;
}
public UserPreferences(string Name, bool SaveOnClose)
{
this.Name = Name;
this.SaveOnClose = SaveOnClose;
}
}
Below is the main method-
UserPreferences userPreferences = new UserPreferences("guest");
XmlSerializer serializer = new XmlSerializer(typeof(UserPreferences));
serializer.Serialize(Console.Out, userPreferences);
Below is the output of this code-
<?xml version="1.0" encoding="IBM437"?>
<UserPreferences xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Name="guest" SaveOnClose="false" />
Notice that the parameter SaveOnClose
is false. Is it possible to hide this parameter in this case? Since false
is considered as default value here.
Also If this parameter is hidden and I deserialize the above XML, parameter SaveOnClose
should be assumed as false
.
Yes, it is possible.
Add a method ShouldSerializeSaveOnClose() and let it return false if the property SaveOnClose should not be serialized.
public bool ShouldSerializeSaveOnClose() {
return SaveOnClose == true;
}
Or, instead of adding a method you can also add a property Specified. Also, add an XmlIgnore attribute on that property to prevent that it gets serialized.
[XmlIgnore]
public bool SaveOnCloseSpecified
{
get { return SaveOnClose == true; }
}
Try the code below: when you specify the 2nd argument in constructor, the attribute is returned in xml. else its hidden.
private bool hasDefaultValue = false;
[XmlAttributeAttribute("Name")]
public string Name;
[XmlAttribute("SaveOnClose")]
public bool SaveOnClose;
[XmlIgnore]
public bool SaveOnCloseSpecified
{
get { return hasDefaultValue; }
}
public UserPreferences() { }
public UserPreferences(string Name)
{
this.Name = Name;
}
public UserPreferences(string Name, bool SaveOnClose)
{
this.Name = Name;
this.SaveOnClose = SaveOnClose;
hasDefaultValue = true;
}
when you have new UserPreferences("guest",false); you should get output as
<UserPreferences ... Name="guest" SaveOnClose="false" />
for new UserPreferences("guest",true); you should get output as
<UserPreferences ... Name="guest" SaveOnClose="true" />
for new UserPreferences("guest") you should get output as
<UserPreferences ... Name="guest">
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