I\'m serializing a class like this
public MyClass
{
public int? a { get; set; }
public int? b { get; set; }
public int? c { get; set; }
}
Yet Another Solution: regex to the rescue, use \s+<\w+ xsi:nil="true" \/>
to remove all null properties from a string containing XML.
I agree, not the most elegant solution, and only works if you only have to serialize. But that was all I needed today, and I don't wanted to add {Foo}Specified
properties for all the properties that are nullable.
public string ToXml()
{
string result;
var serializer = new XmlSerializer(this.GetType());
using (var writer = new StringWriter())
{
serializer.Serialize(writer, this);
result = writer.ToString();
}
serializer = null;
// Replace all nullable fields, other solution would be to use add PropSpecified property for all properties that are not strings
result = Regex.Replace(result, "\\s+<\\w+ xsi:nil=\"true\" \\/>", string.Empty);
return result;
}