I have
public bool Included { get; set; }
That I want to change to:
public bool IsIncluded { get; set; }
I want to have backward compatibility. I'd like to only have IsIncluded defined in code but being able to read old xml where the property would be "Included".
Does XmlSerializer support it and how ?
Note: I tried without success... (does not deserialize it)
public bool IsIncluded { get; set; }
[Obsolete]
public bool Included
{
set { IsIncluded = value; }
get { return IsIncluded; }
}
Update I just want to add that I prefer my solution because I wanted that my xml become IsIncluded which, to me, is more appropriate. Doing as I did (solution below), would enable me to change the xml but keeping previous version working fine. In long term, I would probably be able to remove code to support old version.
Update 2018-02-01 Please take a look at Greg Petersen comment below solution and proposed solution. He propose a great solution in order to encapsulate the correction at the place (the class) where it should be done. WOW!!!
I found it. This is how I did it.
// ******************************************************************
public static SimulScenario LoadFromFile(string path)
{
if (!File.Exists(path))
{
return new SimulScenarioError(path);
}
SimulScenario simulScenario = null;
XmlTextReader reader = new XmlTextReader(path);
XmlSerializer x = new XmlSerializer(typeof(SimulScenario));
x.UnknownAttribute +=x_UnknownAttribute;
x.UnknownElement += x_UnknownElement;
x.UnknownNode += x_UnknownNode;
x.UnreferencedObject += x_UnreferencedObject;
try
{
simulScenario = (SimulScenario)x.Deserialize(reader);
}
catch (Exception)
{
return new SimulScenarioError(path);
}
finally
{
reader.Close();
}
return simulScenario;
}
static void x_UnreferencedObject(object sender, UnreferencedObjectEventArgs e)
{
}
static void x_UnknownNode(object sender, XmlNodeEventArgs e)
{
}
static void x_UnknownElement(object sender, XmlElementEventArgs e)
{
var simulChangeState = e.ObjectBeingDeserialized as SimulChangeState;
if (simulChangeState != null)
{
if (e.Element.Name == "Included")
{
bool val;
if (bool.TryParse(e.Element.InnerText, out val))
{
simulChangeState.IsIncluded = val;
}
else
{
throw new FileFormatException(Log.Instance.AddEntry(LogType.LogError, "Invalid scenario file format."));
}
}
}
}
static void x_UnknownAttribute(object sender, XmlAttributeEventArgs e)
{
}