當我得到這個代碼忽略未知類型:反序列化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));
}
}
第一個測試工作,但是當我運行第二個我得到這個錯誤:
System.InvalidOperationException : There is an error in XML document (2, 9). ----> System.InvalidOperationException : The specified type was not recognized: name='Hello', namespace='', at .
非但沒有這樣的錯誤我希望它忽略未識別的類型。有沒有辦法做到這一點?
我認爲這將是訂閱的一個或多個['Unknown'-事件]的的情況下(http://msdn.microsoft.com/en-us/ library/0a51hxdw.aspx),但嘗試它似乎沒有幫助。神祕。 – AakashM
我也認爲,結果很奇怪。儘管我沒有設法找到解決方案。 – flindeberg