How to exclude null properties when using XmlSerializer

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

    Yet Another Solution: regex to the rescue, use \s+<\w+ xsi:nil="true" \/> to remove all null properties from a string containing XML. I agree, not the most elegant solution, and only works if you only have to serialize. But that was all I needed today, and I don't wanted to add {Foo}Specified properties for all the properties that are nullable.

    public string ToXml()
    {
        string result;
    
        var serializer = new XmlSerializer(this.GetType());
    
        using (var writer = new StringWriter())
        {
            serializer.Serialize(writer, this);
            result = writer.ToString();
        }
    
        serializer = null;
    
        // Replace all nullable fields, other solution would be to use add PropSpecified property for all properties that are not strings
        result = Regex.Replace(result, "\\s+<\\w+ xsi:nil=\"true\" \\/>", string.Empty);
    
        return result;
    }
    

提交回复
热议问题