Reputation: 7230
I have an XML file that I need to deserialize into an object similar to this one:
public class TestObject
{
public string Name { get; set; }
public int Size { get; set; }
public TestObject()
{
Name = string.Empty;
Size = 0;
}
}
My deserialize method looks like this:
private TestObject DeserializeConfiguration(string xmlFileName)
{
XmlSerializer deserializer = new XmlSerializer(typeof(TestObject));
TextReader textReader = new StreamReader(xmlFileName);
TestObject testObj = (TestObject)deserializer.Deserialize(textReader);
textReader.Close();
return testObj;
}
This is working well enough for me but on occasion, I get an XML file that may contain an invalid data type (by "invalid", I mean with respect to the type of the object property that it should map to). For example, if my XML file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<TestObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>Orion</Name>
<Size>abc</Size>
</TestObject>
Obviously I can't convert "abc" into the integer Size property of my object. When I attempt to deserialize this, I see an InvalidOperationException and, not surprisingly, the InnerException is "Input string was not in a correct format". Is it possible to catch this error, use a default value for that property of my object and continue deserializing the remainder of the XML file? If not, can anyone tell me if there's a generally regarded "best practice" for handling invalid data during deserialization?
Upvotes: 3
Views: 2678
Reputation: 33139
What you would need to do is to validate the incoming XML before deserializing. Basically you want to avoid having to process badly-formed XML. After validation the deserializer can at least be sure that all incoming XML will be deserializable.
You can create an XML Schema that contains the definition of valid XML in your case, and then validate the incoming XML with the XSD (XML Schema Definition) first (see also http://www.codeguru.com/csharp/csharp/cs_data/xml/article.php/c6737/Validation-of-XML-with-XSD.htm for more details).
Good luck!
Upvotes: 3