How to exclude null properties when using XmlSerializer

前端 未结 9 1549
谎友^
谎友^ 2021-02-02 07:11

I\'m serializing a class like this

public MyClass
{
    public int? a { get; set; }
    public int? b { get; set; }
    public int? c { get; set; }
}
         


        
9条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-02 08:04

    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);
    

提交回复
热议问题