How to exclude null properties when using XmlSerializer

前端 未结 9 1546
谎友^
谎友^ 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:01

    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.

    0 讨论(0)
  • 2021-02-02 08:03

    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; }
    
    0 讨论(0)
  • 2021-02-02 08:04

    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);
    
    0 讨论(0)
提交回复
热议问题