0

Do I need to take care of validating the XML string I am deserializing against my schema documents, or do i rely on the Deserialization process to do this? (i.e. detect error in deserialization process instead)

Harshana Narangoda
  • 765
  • 1
  • 8
  • 23
erotavlas
  • 3,335
  • 2
  • 34
  • 75
  • 1
    No, just catch the errors. – Patrick Hofman Apr 25 '14 at 15:10
  • @PatrickHofman like maybe by using CanDeserialize() method? – erotavlas Apr 25 '14 at 15:17
  • 1
    What's the point of going through the deserialization twice? – Patrick Hofman Apr 25 '14 at 15:24
  • 1
    @PatrickHofman It's [often considered poor practice to design](http://stackoverflow.com/questions/729379/why-not-use-exceptions-as-regular-flow-of-control) your code to rely on exceptions as a part of regular operations. When available, you should check things before doing an operation that would cause an exception. So `CanDeserialize()` would be a great way to do this. – mason Apr 25 '14 at 16:40

2 Answers2

1

It depends where you are getting your XML from - if its from a non-trusted source (i.e. you didn't write it; its just a stream or file with an XML extension) then use an XmlValidatingReader class instance.

Just because something comes with an ".xml" file extension it doesn't mean its XML. Also depends on the frequency of calls - I wouldn't bother validating the return from a SOAP call for instance, because there is a higher level of conformance checking in my WCF/SOAP library.

PhillipH
  • 5,938
  • 1
  • 13
  • 24
0

Schema validation should occur on the write. You need to catch any errors on the deserialization--but it doesn't really matter what those errors are due to. e.g. you could validate against the schema and still get a deserialization error.

Peter Ritchie
  • 33,368
  • 9
  • 74
  • 96