How to exclude null properties when using XmlSerializer

前端 未结 9 1567
谎友^
谎友^ 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 07:47

    If you make the class you want to serialise implement IXmlSerializable, you can use the following writer. Note, you will need to implement a reader, but thats not too hard.

        public void WriteXml(XmlWriter writer)
        {
            foreach (var p in GetType().GetProperties())
            {
                if (p.GetCustomAttributes(typeof(XmlIgnoreAttribute), false).Any())
                    continue;
    
                var value = p.GetValue(this, null);
    
                if (value != null)
                {
                    writer.WriteStartElement(p.Name);
                    writer.WriteValue(value);
                    writer.WriteEndElement();
                }
            }
        }
    

提交回复
热议问题