Neil
Neil

Reputation: 197

C# XML Serialization int tag value not supplied

I have a class that can be serialized. One of the properties is an int, and if a value isn't supplied for the field, the tag is still present but with a zero value, because an int cannot by null of course.

The problem i have is that the client who wants to recieve the xml doesn't want to see the tag at all if a value has not been supplied. They do not want to to see the tag with a 0 value.

Any ideas?

Upvotes: 1

Views: 3414

Answers (2)

J. Tihon
J. Tihon

Reputation: 4459

If you apply the [DefaultValue(0)] attribute to the property, the value is only serialized if it differs from that value:

Short example:

class Program
{
    static void Main(string[] args)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Serialized));
        Serialized s = new Serialized();
        serializer.Serialize(Console.Out, s);

        Serialized s2 = new Serialized { Value = 10 };
        serializer.Serialize(Console.Out, s2);

        Console.ReadLine();
    }
}

public class Serialized
{
    [XmlAttribute]
    [DefaultValue(0)]
    public int Value { get; set; }
}

The first serialized object does not have a Value-attribute, where the second one which has a Value other than 0 is written.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1063338

If you make it an int? it will be suppressed when null:

public int? Foo { get; set; }

You can also hide this on your object's API:

private int? foo;
public int Foo {
    get { return foo.GetValueOrDefault(); }
    set { foo = value; }
}
public bool ShouldSerializeFoo() { return foo.HasValue;}

where ShouldSerialize* is a pattern recognised automatically by XmlSerializer

Upvotes: 3

Related Questions