I\'m serializing a class like this
public MyClass
{
public int? a { get; set; }
public int? b { get; set; }
public int? c { get; set; }
}
I suppose you could create an XmlWriter that filters out all elements with an xsi:nil attribute, and passes all other calls to the underlying true writer.
Better late than never...
I found a way (maybe only available with the latest framework I don't know) to do this. I was using DataMember attribute for a WCF webservice contract and I marked my object like this:
[DataMember(EmitDefaultValue = false)]
public decimal? RentPrice { get; set; }
1) Extension
public static string Serialize<T>(this T value) {
if (value == null) {
return string.Empty;
}
try {
var xmlserializer = new XmlSerializer(typeof(T));
var stringWriter = new Utf8StringWriter();
using (var writer = XmlWriter.Create(stringWriter)) {
xmlserializer.Serialize(writer, value);
return stringWriter.ToString();
}
} catch (Exception ex) {
throw new Exception("An error occurred", ex);
}
}
1a) Utf8StringWriter
public class Utf8StringWriter : StringWriter {
public override Encoding Encoding { get { return Encoding.UTF8; } }
}
2) Create XElement
XElement xml = XElement.Parse(objectToSerialization.Serialize());
3) Remove Nil's
xml.Descendants().Where(x => x.Value.IsNullOrEmpty() && x.Attributes().Where(y => y.Name.LocalName == "nil" && y.Value == "true").Count() > 0).Remove();
4) Save to file
xml.Save(xmlFilePath);