Skip to content

Instantly share code, notes, and snippets.

@makomweb
Last active December 28, 2015 07:39
Show Gist options
  • Save makomweb/7465691 to your computer and use it in GitHub Desktop.
Save makomweb/7465691 to your computer and use it in GitHub Desktop.
Deserializing an old scheme with polymorphic types into a new one using .NET facilities. The basic problem is that the XML bears the xsi information inside the Person element which enables the deserializer to create concrete types. This way you can make the deserializer happy about even though you don't need the specific information from the con…
[TestFixture]
public class Deserialize_a_different_scheme
{
[XmlType("Archive")]
public class Archive
{
[XmlType("Person")]
[XmlInclude(typeof(Employee))]
public class Person
{
public string Name { get; set; }
}
public class Employee : Person
{
public string Company { get; set; }
}
public Person[] Folks { get; set; }
}
[XmlType("Archive")]
public class NewArchive
{
[XmlType("Person")]
[XmlInclude(typeof(NewEmployee))]
public class NewPerson
{
string Name { get; set; }
}
[XmlType("Employee")]
public class NewEmployee : NewPerson
{
public int Foobar { get; set; }
}
public NewPerson[] Folks { get; set; }
}
[Test]
public void Deserialize_persons_should_succeed()
{
const string path = @"c:\Temp\Data.xml";
var archive = new Archive
{
Folks = new[]
{
new Archive.Person { Name = "Fritz" },
new Archive.Employee { Name = "Karla", Company = "ABC" }
}
};
using (var output = File.OpenWrite(path))
{
using (var writer = XmlWriter.Create(output))
{
var serializer = new XmlSerializer(typeof(Archive));
serializer.Serialize(writer, archive);
}
}
using (var input = File.OpenRead(path))
{
using (var reader = XmlReader.Create(input))
{
var serializer = new XmlSerializer(typeof(NewArchive));
var newArchive = (NewArchive)serializer.Deserialize(reader);
Assert.AreEqual(archive.Folks.Length, newArchive.Folks.Length);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment