using System.Collections.Generic;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Globalization;
public static partial class XmlSerializerExtensions
public static object DeserializePolymorphicXml(this string xml, params Type[] types)
using (var textReader = new StringReader(xml))
return textReader.DeserializePolymorphicXml(types);
public static object DeserializePolymorphicXml(this TextReader textReader, params Type[] types)
if (textReader == null || types == null)
throw new ArgumentNullException();
var settings = new XmlReaderSettings { CloseInput = false };
using (var xmlReader = XmlReader.Create(textReader, settings))
foreach (var type in types)
var serializer = new XmlSerializer(type);
if (serializer.CanDeserialize(xmlReader))
return serializer.Deserialize(xmlReader);
throw new XmlException("Invalid root type.");
public static partial class XmlSerializerExtensions
public static string GetXml<T>(this T obj, bool omitStandardNamespaces)
XmlSerializerNamespaces ns = null;
if (omitStandardNamespaces)
ns = new XmlSerializerNamespaces();
using (var textWriter = new StringWriter())
var settings = new XmlWriterSettings() { Indent = true };
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
new XmlSerializer(obj.GetType()).Serialize(xmlWriter, obj, ns);
return textWriter.ToString();
public class SuccessResponse
public string Value { get; set; }
public class FailResponse
public string Message { get; set; }
public static void Test()
Test(new SuccessResponse { Value = "my value" }.GetXml(true));
Test(new FailResponse { Message = "failure message" }.GetXml(true));
Console.WriteLine("Done");
public static void Test(string xml)
Console.WriteLine("Input XML: ");
var xmlBody = xml.DeserializePolymorphicXml(typeof(SuccessResponse), typeof(FailResponse));
Console.WriteLine(string.Format("Deserialized response of type: {0}", xmlBody.GetType()));
if (xmlBody is SuccessResponse)
Console.WriteLine(string.Format("Successful response, Value = {0}", ((SuccessResponse)xmlBody).Value));
else if (xmlBody is FailResponse)
Console.WriteLine(string.Format("Failure response, Message = {0}", ((FailResponse)xmlBody).Message));
throw new InvalidOperationException("unknown response");
Console.WriteLine("Re-serialized XML: ");
Console.WriteLine(xmlBody.GetXml(true));
public static void Main()
Console.WriteLine("Environment version: " + Environment.Version);