I have an XML file that is validated against an XSD file. When a validation exception occurs, the handler is called:
ValidationCallBack(object sender, System.Xml.Schema.ValidationEventArgs args)
I have the exception thrown by the framework, but I need to customize this exception in order to have the XSD line that have thrown this error and also the value from the XML that was not correct. Ca开发者_Go百科n I parse the exception's message in order to extract this kind of information? I mean, can I rely on a regular expression for this?
You can get this information from Exception
member.
static void ValidationCallback(object sender, ValidationEventArgs args)
{
// Not sure if the exception is guaranteed to not be null.
if (args.Exception != null)
{
// Remember to always retain the InnerException (last argument is args.Exception).
throw new MyException(args.Exception.LineNumber, args.Exception.LinePosition, args.Exception.Message, args.Exception);
}
// If the exception is null do what we can.
throw new MyException(-1, -1, args.Message, args.Exception);
}
EDIT: Just noticed that you wanted the original element/thing that caused the problem. Firstly, you can get the schema entity that caused the validation problem from SchemaObject
. Getting the original item that caused the problem is way more difficult. You are probably going to have to re-read the document (with a non-validating reader) and search for the node with the matching line/position.
Side note: Please don't use regex, ever. You will get really nasty problems if your application is run on another locale: as all the built-in .Net exceptions have translations (so your regex won't work).
You can find the details of the validation exception by looking at the public properties of the XmlSchemaException class (the instances of which are available via the Exception
property of the args
argument):
- LineNumber
- LinePosition
- SourceSchemaObject
I have found the solution, by using the xmlns:ex="anySchemaNamespace" attribute for the xsd document element. Then, I can add for example this unhandled attribute ex:exception="My custom exception" to any element and then take that custom exception message from the element in code, when an exception occurs. Thanks for your answers.
精彩评论