using System.Xml.Serialization;
public static void Main()
ResponseBase result1 = Deserialize("<?xml version=\"1.0\"?>\r\n <root>\r\n <elementOne>101</elementOne>\r\n <elementTwo>10</elementTwo>\r\n </root>");
ResponseBase result2 = Deserialize("<?xml version=\"1.0\"?>\r\n <root>\r\n <elementOne>101</elementOne>\r\n <elementTwo>10</elementTwo>\r\n <elementThree>10</elementThree>\r\n </root>");
private static void PrintResult(ResponseBase result)
if(result is DerivedOneClass)
DerivedOneClass derived = (DerivedOneClass)result;
Console.WriteLine("Result is of type 'DerivedOneClass': {0}, {1}", derived.ElementOne, derived.ElementTwo);
else if(result is DerivedTwoClass)
DerivedTwoClass derived = (DerivedTwoClass)result;
Console.WriteLine("Result is of type 'DerivedTwoClass': {0}, {1}, {2}", derived.ElementOne, derived.ElementTwo, derived.ElementThree);
private static ResponseBase Deserialize(string xml)
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
XmlSerializer serializer = new XmlSerializer(typeof(ResponseBase));
XmlDocument document = new XmlDocument();
AddTypeDefinition(document);
XmlReader reader = new XmlNodeReader(document);
ResponseBase result = serializer.Deserialize(reader) as ResponseBase;
private static void AddTypeDefinition(XmlDocument document)
const string xsiNamespaceUri = "http://www.w3.org/2001/XMLSchema-instance";
XmlNode node = document.SelectSingleNode("root");
if (node == null) return;
var typeAttribute = node.Attributes["type", xsiNamespaceUri];
if (typeAttribute != null) return;
string type = "DerivedOneClass";
XmlNodeList nodes = node.SelectNodes("//elementThree");
if (nodes != null && nodes.Count > 0)
type = "DerivedTwoClass";
XmlAttribute attribute = document.CreateAttribute("xsi", "type", xsiNamespaceUri);
node.Attributes.Append(attribute);
[XmlInclude(typeof(DerivedOneClass))]
[XmlInclude(typeof(DerivedTwoClass))]
[XmlRoot(ElementName = "root")]
public class ResponseBase
public class DerivedOneClass: ResponseBase
[XmlElementAttribute("elementOne")]
public string ElementOne {get; set;}
[XmlElementAttribute("elementTwo")]
public string ElementTwo {get; set;}
public class DerivedTwoClass: ResponseBase
[XmlElementAttribute("elementOne")]
public string ElementOne {get; set;}
[XmlElementAttribute("elementTwo")]
public string ElementTwo {get; set;}
[XmlElementAttribute("elementThree")]
public string ElementThree {get; set;}