I have xml file:
<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 simple classes
public class Name
{
[XmlElement("ID")]
public int Id { get; set; }
}
[XmlRoot("TestType")]
[Serializable]
public class TestType
{
public Collection<Name> Names { get; set; }
}
and try to deserialize xml file:
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();
}
as expected in default behaviour, deserialize throw InvalidOperationException, "invalid input string" on element where id = 2WRONG(is string,not int), and deserialization process abort. In book.Names collection zero elements.
How i can do this:
1) deserialize process dont abort on wrong entry, his throw exception, i catch him and process continue. 2) book.Names collection after deserialization contain all right elements((id=0,1,3) in this case)
PS: I tried to mix validation and deserialization, yes. I do this because deserialization is very fast,this important for me. If i do this wrong - show me the way please.