The XML Data Model does a lot of validation when it loads an XML document, but in some instance it does not capture all the validation rules contained within the XML Schema, so it is sometimes beneficial to validate the XML data using the original XML schemas.
If the code is generated setting 'Add XSD Validation Code' is set to true, then the original XSD schemas are embedded into the assembly as resources, and a validation class is generated (the name of the validation class is taken from the setting 'XSD Validation Class name').
This class can the be used to validate XML documents or create a validating XmlReader. This makes it possible easily validate an XML document as its loaded.
The following code shows how to create a validating XmlReader that is used to validate the XML data before the Liquid XML Objects serializer goes to work on it.
Validating Reader Example |
Copy Code
|
---|---|
static void Main(string[] args) { BookStoreValidator validator = new BookStoreValidator(); using (XmlReader validatingReader = validator.CreateValidatingReader(@"..\..\BookstoreSample.xml", ValidatingReaderErrorHandler)) { LxSerializer<BookstoreElm> serializer = new LxSerializer<Bs.BookstoreElm>(); LxReaderSettings lxReaderSettings = new LxReaderSettings() { ErrorHandler = LxErrorHandler }; BookstoreElm bookstoreElm = serializer.Deserialize(validatingReader, lxReaderSettings); foreach (var book in bookstoreElm.Book) Console.WriteLine($"book : {book.Title} by {book.Author.First_Name} {book.Author.Last_Name}"); } } private static void ValidatingReaderErrorHandler(object sender, ValidationEventArgs e) { Debug.WriteLine($".Net XSD Validator : {e.Severity} : {e.Message}"); } private static void LxErrorHandler(string msg, LxErrorSeverity severity, LxErrorCode errorCode, TextLocation location, object targetObject) { Debug.WriteLine($"Liquid XML Objects Validator : {severity} : {msg}"); } |
When the code runs with an invalid genre value in the XML it outputs the following trace. The first entry is the one from the validating reader, as this is ignored in the ValidatingReaderErrorHandler, it is allowed to pass to the Liquid XML Objects serializer, which also reports the issue. Typically the ValidatingReaderErrorHandler implementation would throw an exception when an error is reported.
Trace Output |
Copy Code
|
---|---|
XSD Validator : Error : The 'http://www.liquid-technologies.com/sample/bookstore:genre' element is invalid - The value 'ERROR_UNKNOWN_GENRE' is invalid according to its datatype 'String' - The Enumeration constraint failed. Liquid XML Objects Validator : Error : The value of the element genre@http://www.liquid-technologies.com/sample/bookstore can not be read into property XsdValidation.Bs.BookTypeCt+BookTypeSeq.Genre. The value 'ERROR_UNKNOWN_GENRE' could not be converted to the enumeration type XsdValidation.Bs.BookTypeCt+GenreEnum |