Search code examples
xmlexceptionxmldocumentxml-validation

XmlDocument.Validate() - get error message from exception


Is it possible to return the errors from Xml.Validate(...)? i.e. the point at which my xml fails to validate against the xsd.

In this snippet the validation would simply fail the try-catch, and return false. Removing the try-catch throws a system exception.

Note: 'var Xml' is of type XmlDocument.

public static class XmlValidator
{
    public static bool Validate(UploadedFile uploadedFile)
    {
        try
        {
            var Xml = uploadedFile.XmlFromUpload();
            string XsdPath = @"C:\Projects\XMLValidator\Xsd\books.xsd";

            Xml.Schemas.Add(null, XsdPath);
            Xml.Validate(ValidationCallBack);
            return true;
        }
        catch
        {
            return false;
        }
    }

    private static void ValidationCallBack(object sender, ValidationEventArgs e)
    {
        throw new Exception();
    }
}

Solution

  • The ValidationEventArgs parameter of the ValidationCallBack contains the error: https://msdn.microsoft.com/en-us/library/system.xml.schema.validationeventargs%28v=vs.110%29.aspx

    It has Exception, Message and Severity properties. Consider saving these and then making them available, e.g.:

    public static class XmlValidator
    {
        public static bool Validate(UploadedFile uploadedFile)
        {
            _errors.Clear();
            var Xml = uploadedFile.XmlFromUpload();
            string XsdPath = @"C:\Projects\XMLValidator\Xsd\books.xsd";
    
            Xml.Schemas.Add(null, XsdPath);
            Xml.Validate(ValidationCallBack);
            return !_errors.Any();
        }
    
        private static void ValidationCallBack(object sender, ValidationEventArgs e)
        {
            _errors.Add(e.Exception);
        }
    
        private static List<Exception> _errors = new List<Exception>();
    
        public static IEnumerable<Exception> GetErrors() 
        {
            return _errors;
        }
    }