I am using the XmlSerializer and have the following property in a class
public string Data { get; set; }
which I need to be output exactly like
try to use public bool ShouldSerialize_PropertyName_(){} with setting the default value inside.
public bool ShouldSerializeData()
{
Data = Data ?? "";
return true;
}
Description of why this works can be found on MSDN.
The solution to this was to create a PropertyNameSpecified
property that the serializer uses to determine whether to serialize the property or not. For example:
public string Data { get; set; }
[XmlIgnore]
public bool DataSpecified
{
get { return !String.IsNullOrEmpty(Data); }
set { return; } //The serializer requires a setter
}
You could try adding the XMLElementAttribute like [XmlElement(IsNullable=true)]
to that member. That will force the XML Serializer to add the element even if it is null.
I was recently doing this and there is an alternative way to do it, that seems a bit simpler. You just need to initialise the value of the property to an empty string then it will create an empty tag as you required;
Data = string.Empty;
You could try adding the XMLElementAttribute like [XmlElement(IsNullable=true)] to that member and also set in the get/set property something like this:
[XmlElement(IsNullable = true)]
public string Data
{
get { return string.IsNullOrEmpty(this.data) ? string.Empty : this.data; }
set
{
if (this.data != value)
{
this.data = value;
}
}
}
private string data;
And so you will not have:
<Data xsi:nil="true" />
You will have this on render:
<Data />