16

I have a problem deserializing some XML; the XML supplied by a third party is quite verbose, so if there is no value set for an particular element, it will supply and empty element (e.g. <element1 />).

This is a problem for certain elements, for example, those that are meant to store integers. I have control over the third party, so I could either get them to specify a default value (<myinteger>0</myinteger>) or I can get them to omit these elements entirely. Both of these should avoid the problem.

However, there may be situations in future, where we don't have so much control - in which case, is there a way of specifying, perhaps via a decoration, a default value?

    [XmlElement("myinteger")=0???]
    public int MyInteger
    {
        get
        {
            return myInteger;
        }
        set
        {
            myInteger= value;
        }
    }
CJM
  • 11,908
  • 20
  • 77
  • 115

2 Answers2

43

XmlSerializer does support [DefaultValue], but it uses it during serialization. During deserialization, it simply runs the constructor, then takes incoming values and applies them. A common approach, then, is to use the constructor (or field-initializers):

public Foo() {
    Bar = 4;
}
[DefaultValue(4), XmlAttribute("bar")]
public int Bar {get;set;}

However; XmlSerializer's interpretation of this is not "supply an empty element" - but rather "omit the element(/attribute)". Even int? doesn't map to "empty". To handle empty elements, you would have to handle it as a string. Which is ugly.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    Hmmmm... simply getting the third party to omit empty elements of a description seems the easiest solution. I was just curious what I could do where I didn't have the luxury of that choice. I did consider the string option, but it is just an big can of worms... – CJM Aug 16 '10 at 11:08
  • There is at least one important effect during deserialization. If the element is empty, without DefaultValue there may be a parsing error. However, with it, the [generated code](http://msdn.microsoft.com/en-us/library/aa302290.aspx) will skip the empty element. – Matthew Flaschen Jul 07 '12 at 02:14
0

Decoration using [DefaultValue] doesn't seem to be complete solution since it doesnt work always. Another simple Solution (May not be clean)

public string _sourceSubFolderName;
    [DefaultValueAttribute("")]
    [XmlElement("SourceSubFolderName")]
    public string SourceSubFolderName
    {
        get { return string.IsNullOrEmpty(_sourceSubFolderName) ? 
               string.Empty : _sourceSubFolderName; }
        set { _sourceSubFolderName = value; }
    }
Ram
  • 15,908
  • 4
  • 48
  • 41