C# Get schema information when validating xml
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?
XmlNode.SchemaInfo
seems like it will provide this information.
I assume this will be populated when an XmlDocument
is loaded using an XmlReader
created to perform XSD validation.
However when performing validation the handler for validation errors (XmlReaderSettings.ValidationEventHandler
) there is only limited information available in the XmlSchemaException
instances passed with the ValidationEventArgs
). In particular there is no XmlNode
or similar reference into the input document. There is however a reference to the SourceSchemaObject
.
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.
List<XmlElement> errorElements = new List<XmlElement>();
serializedObject.Validate((x, y) =>
{
var exception = (y.Exception as XmlSchemaValidationException);
if (exception != null)
{
var element = (exception.SourceObject as XmlElement);
if (element != null)
errorElements.Add(new XmlValidationError(element));
}
});
精彩评论