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?
Generic solution for similar problems:
Have a look at unknown element event (link) and unknown attribute event (link) and see if they solve the problems, or we have to get dirty. Read on…
Working solution for this problem
Bear in mind that that I have no idea what your task is, AFAIK it is serializing xml into your datastructure. If you can change the datastructure I would recommend you to have a look at Linq2XML and create a smart factory for your purposes.