XmlDocument.Validate() - 从异常中获取错误信息
XmlDocument.Validate() - get error message from exception
是否可以 return 来自 Xml.Validate(...) 的错误?即我的 xml 无法验证 xsd.
在此代码段中,验证只会使 try-catch 失败,并且 return 错误。删除 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();
}
}
ValidationCallBack 的 ValidationEventArgs 参数包含错误:
https://msdn.microsoft.com/en-us/library/system.xml.schema.validationeventargs%28v=vs.110%29.aspx
它具有异常、消息和严重性属性。考虑保存这些然后使它们可用,例如:
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;
}
}
是否可以 return 来自 Xml.Validate(...) 的错误?即我的 xml 无法验证 xsd.
在此代码段中,验证只会使 try-catch 失败,并且 return 错误。删除 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();
}
}
ValidationCallBack 的 ValidationEventArgs 参数包含错误: https://msdn.microsoft.com/en-us/library/system.xml.schema.validationeventargs%28v=vs.110%29.aspx
它具有异常、消息和严重性属性。考虑保存这些然后使它们可用,例如:
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;
}
}