I've got this code:
[XmlType( "Metadata" )]
[Serializable]
public class MetadataContainer : List<MetadataBase>
{
}
[XmlType( "Meta" )]
[XmlInclude( typeof( ReadonlyMetadata ) )]
[Serializable]
public abstract class MetadataBase
{
}
[XmlType( "Readonly" )]
[Serializable]
public class ReadonlyMetadata : MetadataBase
{
}
[TestFixture]
public class SerializationTests
{
[Test]
public void Can_deserialize_with_known_type()
{
const string text = @"<Metadata xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<Meta xsi:type=""Readonly"" />
</Metadata>";
var serializer = new XmlSerializer( typeof( MetadataContainer ) );
var metas = (MetadataContainer)serializer.Deserialize( XmlReader.Create( new StringReader( text ) ) );
Assert.That( metas.Count, Is.EqualTo( 1 ) );
Assert.That( metas.First(), Is.InstanceOf<ReadonlyMetadata>() );
}
[Test]
public void Can_deserialize_with_unknown_type()
{
const string text = @"<Metadata xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<Meta xsi:type=""Hello"" />
</Metadata>";
var serializer = new XmlSerializer( typeof( MetadataContainer ) );
var metas = (MetadataContainer)serializer.Deserialize( XmlReader.Create( new StringReader( text ) ) );
Assert.That( metas.Count, Is.EqualTo( 0 ) );
}
}
The first test works, but when I run the second I get this error:
System.InvalidOperationException : There is an error in XML document (2, 9). ----> System.InvalidOperationException : The specified type was not recognized: name='Hello', namespace='', at .
Instead of getting this error I would like it to ignore not recognized types. Is there any way to do this?