XmlDocument.Validate() - 从异常中获取错误消息

时间:2015-02-18 10:03:11

标签: xml exception-handling xmldocument xml-validation

是否可以从Xml.Validate(...)返回错误?即我的xml无法对xsd进行验证的点。

在这个片段中,验证只会使try-catch失败,并返回false。删除try-catch会引发系统异常。

注意:' var Xml'是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();
    }
}

1 个答案:

答案 0 :(得分:1)

ValidationCallBack的ValidationEventArgs参数包含错误: https://msdn.microsoft.com/en-us/library/system.xml.schema.validationeventargs%28v=vs.110%29.aspx

它具有Exception,Message和Severity属性。考虑保存这些,然后使它们可用,例如:

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;
    }
}