I am facing a challenge deserializing an XML to appropriate type. Request your help.
I have two xml files. oldXML.xml and newXML.xml below respectively
<?xml version="1.0"?>
<root>
<elementOne>101</elementOne>
<elementTwo>10</elementTwo>
</root>
And
<?xml version="1.0"?>
<root>
<elementOne>101</elementOne>
<elementTwo>10</elementTwo>
<elementThree>10</elementThree>
</root>
newXML.xml has an additional attribute "elementThree"
I have written 3 classes to desirialize the XMLs into
public abstract class ResponseBase
{
public abstract void PrintResult();
}
public class OldXML : ResponseBase
{
[XmlElement("elementOne")]
public string ElementOne { get; set; }
[XmlElement("elementTwo")]
public string ElementTwo { get; set; }
public override void PrintResult()
{
Console.WriteLine("Result is of type 'OldXML': {0}, {1}", ElementOne, ElementTwo);
}
}
public class NewXML : ResponseBase
{
[XmlElement("elementOne")]
public string ElementOne { get; set; }
[XmlElement("elementTwo")]
public string ElementTwo { get; set; }
[XmlElement("elementThree")]
public string ElementThree { get; set; }
public override void PrintResult()
{
Console.WriteLine("Result is of type 'NewXML': {0}, {1}, {2}", ElementOne, ElementTwo, ElementThree);
}
}
And I want to deserialize them as below
ResponseBase result1= MethodToDeserializeToBeWritten(File.ReadAllText("oldXML.json"))
ResponseBase result2= MethodToDeserializeToBeWritten(File.ReadAllText("newXML.json"))
result1.PrintResult()
result2.PrintResult()
When I Invoke PrintResult method, at the mercy of polymorphism in OOPS, child class implementation should be invoked (Not working, throws an error that abstract class cannot be instantiated). Please note that these XMLs are just examples and the code should work for any such XMLs.
Also, the XML is received from a client and hence we cannot change the XML.
The reason for doing this is, in future, we might get a new XML with new attribute say "elementFour". For that, we will be adding a new class and not touching the existing implementation.
Thanks in advance.