Search code examples
c#.netxml-serialization

XML Serialization - Eliminate null value elements


Here is my class.

 public class Class1
{
    private int? intValue;
    public int? IntValue
    {
        get { return intValue; }
        set { intValue = value; }
    }

    bool ShouldSerializeIntValue()
    {
        return IntValue != null;  
    }

    private string stringValue;
    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }

    bool ShouldSerializeStringValue()
    {
        return StringValue != null;
    }

    private decimal? decimalValue;
    public decimal? DecimalValue
    {
        get { return decimalValue; }
        set { decimalValue = value; }
    }

    bool ShouldSerializeDecimalValue()
    {
        return DecimalValue != null;
    }

}

}

Here is my XML Serialization code

        private string ToXml(object model)
    {
        if (model != null)
        {
            XmlSerializer Serializer = new XmlSerializer(model.GetType());
            XmlSerializerNamespaces NameSpaces = new XmlSerializerNamespaces();
            NameSpaces.Add("", "");
            StringWriter Writer = new StringWriter();
            XmlWriterSettings Settings = new XmlWriterSettings();
            using (XmlWriter XmlWriter = XmlWriter.Create(Writer))
            {
                Serializer.Serialize(XmlWriter, model,  NameSpaces);
            }
            return Writer.ToString();
        }
        else return null;

    }

When I try to Serialize with null int value, it is serializing like this.

<?xml version="1.0" encoding="utf-16"?><Class1><IntValue p2:nil="true" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance" /><StringValue>Int value is null.</StringValue><DecimalValue>456.789</DecimalValue></Class1>

So instead of serializing like this

<IntValue p2:nil="true" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance" />

I want to eliminate the whole element during serialization when it is null.

I saw there are similar questions but I am not sure what is wrong in this specific class because it always serializes as shown above and I do have the "ShouldSerialize" functions.

How to achieve this ? Any thoughts ?


Solution

  • You should mark ShouldSerialize{PropertyName} methods as public

    public bool ShouldSerializeIntValue()
    {
        return IntValue != null;  
    }