I’m trying to validate some XML against a schema and gather as much information as possible to provide valuable error messages to the user.
I’ve managed to validate a serialized object against an XSD. My ValidationEventHandler is being called properly for all errors and I get get some information there. The only problem is that schema information is not available at this point – I’m trying to get to the schema type of the element. i.e. given the following schema element, I would like to get “BookType”
<element minOccurs="0" maxOccurs="1" name="TypeOfBook" type="myTypes:BookType" />
I believe schema/validation information is being inserted into the xml during the validation process. So if I call validate twice in a row, only handling the erros the second time around, the schema information is available.
serializedObject.Validate((x, y) => { });
serializedObject.Validate((x, y) => { // handle errors here because elements will have schema info available });
Obviously, this solution leaves much to be desired. What is the recommended way of dealing with this?
I found a solution.
Every time the ValidationEventHandler gets called, add the XmlSchemaValidationException.SourceObject Xmlelement to a list. Once validation is complete the schema information would be added to these objects, enabling me to access the information. i.e. Element.SchemaInfo.SchemaType.Name.
An XmlSchemaValidationException gets passed to the event handler with a property “SourceObject ” which is an XmlElement.