简体   繁体   中英

Set default value while XML Deserialization C#

Consider the below class

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Serialized this Person class (Name & Age) with some value in XML file and deserialized return back. I want to assign some default value when Name value is Null or Empty when deserializing. I tried like below, but its not working.

public class Person
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            if (_name == null)
            {
                _name = "Some Name";
            }
        }
    }
}

How to set default value for string and int field when deserializing the C# object using XmlSerializer.

The problem is that you have put logic for the default value in your setter and this is not getting called because there is no data for this in the XML you are deserializing.

When XmlSerializer deserializes, it will first call the constructor and then set the values. So if you want to set defaults, do that in the constructor. Anything you have a deserialized value for will then get applied over it, and those you don't will still have the default.

public class Person 
{
    public Person() 
    {
        Name = "Default Name";
    }

    public string Name { get; set; }
}

You have to initial property inside Contructor like Own Pauling

Or you can auto-initialize like this:

public class Person{
public string Name { get; set; } = "Some name"
public int Age { get; set; } = 18
}

On your code demo.

It just working when you set something (anything, even null ) to the property before Deserialization .

As the other answers also suggest default value should be interpreted as the value, which is assigned to the property by the default constructor.

If you want an XML serializer, which can consider the default values (will not serialize properties with default values) you can try this one (disclaimer: written by me).

Thus you can define your Person class as follows.

public class Person
{
    [DefaultValue("Some Name")]
    public string Name { get; set; } = "Some Name";

    [DefaultValue(50)]
    public int Age { get; set; } = 50;
}

See here a live example. The libraries are available on NuGet . It supports both Linq2Xml ( XElement ) and the regular XmlWriter .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM