我有xml文件:C#反序列化catch和繼續InvalidOperationException。怎麼樣?
<TestType>
<Names>
<Name>
<ID>0</ID>
</Name>
<Name>
<ID>1</ID>
</Name>
<Name>
<ID>2WRONG</ID>
</Name>
<Name>
<ID>3</ID>
</Name>
</Names>
</TestType>
2簡單的類
public class Name
{
[XmlElement("ID")]
public int Id { get; set; }
}
[XmlRoot("TestType")]
[Serializable]
public class TestType
{
public Collection<Name> Names { get; set; }
}
,並嘗試反序列化XML文件:
private static void ReadXml()
{
var book = new TestType(){Names = new Collection<Name>()};
var reader =
new XmlSerializer(typeof(TestType));
var file = new XmlTextReader(
@"c:\temp\stest.xml");
try
{
book = (TestType)reader.Deserialize(file);
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.InnerException.Message);
}
file.Close();
Console.WriteLine(book.Names.Count);
Console.ReadKey();
}
預期違約行爲,反序列化拋出InvalidOperationException異常,「無效輸入字符串「on元素其中id = 2WRONG(是字符串,不是int),並且反序列化過程中止。在book.Names集合中有零個元素。
我怎樣才能做到這一點:
1)反序列化過程中不放棄的輸入錯誤,他拋出異常,我抓住他,進程繼續下去。 2)book.Names集合在反序列化後包含所有正確的元素(在這種情況下(id = 0,1,3))
PS:我試圖混合驗證和反序列化,是的。我這樣做是因爲反序列化非常快,這對我很重要。如果我做錯了 - 請告訴我方式。