I\'m serializing a class like this
public MyClass
{
public int? a { get; set; }
public int? b { get; set; }
public int? c { get; set; }
}
1) Extension
public static string Serialize(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);