How to specify a different default values for XmlElement other than the one in its constructor?

Viewed 97

I have these 2 classes

[XmlType]
public class Child
{
    public Child()
    {
        X = false;
        Y = -100;
    }

    [XmlAttribute]
    public bool X { get; set; }

    [XmlAttribute]
    public int Y { get; set; }
}

[XmlRoot]
public class Parent
{
    public Parent()
    {
        C = new Child()
        {
            X = true;
        }
        ;
    }

    [XmlElement]
    public child C { get; set; }
}

when I try to parse a parent with child object that does not specify a value of x, I need x to be true not false. Example:

string xmlText = "<Parent><C y='1000'/></Parent>";
Parent p;
using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlText)))
{
    using (var reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, XmlDictionaryReaderQuotas.Max, null))
    {
        var xmlDeserializer = new XmlSerializer(typeof(parent));
        p = xmlDeserializer.Deserialize(reader) as Parent;
    }
}
if(p.C.X) 
{
    Console.WriteLine("p.C.X is true");.
}
else
{
    Console.WriteLine("p.C.X is false");
}

Then if we print p.C.X it will be false not true. How to solve this problem?

Note: I have updated the question, X was int in the beginning and then I changed it be bool (that's why the answers will refer to X as an int not a bool).

2 Answers
Related