简体   繁体   中英

XML Deserialization in C#

I have one class which was serialized before. We have the xml output from it. When we open the project we deserialize the xml to get the preserved objects. Now i have added new bool property to class and since it is a new property, old xmls don't have this attribute. My deserialization works fine but assigns false to bool property, I want it to set true if its not there in XML. How can i achieve this ? I tried like this

public bool? _flag;
[XmlElement("Flag")]
public bool? flag
{
    get
    {
        if (null != _flag)
        {
            return _flag;
        }
        return true;
    }
    set { _flag= value; }
}

You just need to add your default constructor and set it there. Here is an example:

public MyObject()
{
    Flag = true;
}

EDIT

I'm not sure what's going on in your code, but this works perfectly fine:

public class MyObject
    {
        public MyObject()
        {
            Flag = true;
        }

        public bool Flag { get; set; }

        public string Name { get; set; }
    }

First, I didn't have the bool property there and serialized it to a file.. then for step 2, I added that bool property and the constructor.. then deserialized it from disk and it showed true , which is what I expected.

Please review your code, as I expect something else is going on. If you need help, post the full class here.

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