ho questo codice:Ignora tipi sconosciuti quando la deserializzazione XML
[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));
}
}
Il primo test funziona, ma quando ho eseguito il secondo ottengo questo errore:
System.InvalidOperationException : There is an error in XML document (2, 9). ----> System.InvalidOperationException : The specified type was not recognized: name='Hello', namespace='', at .
Invece di ottenere questo errore Mi piacerebbe che ignorasse i tipi non riconosciuti. C'è un modo per fare questo?
ho pensato che questo sarebbe un caso di sottoscrizione di uno o più dei [ 'eventi Unknown'-] (http://msdn.microsoft.com/en-us/ library/0a51hxdw.aspx), ma a provarlo sembra non aiutare. Misterioso. – AakashM
Ho pensato anche che, comunque, i risultati sono strani. Non sono riuscito a trovare una soluzione però. – flindeberg