问题
I am trying to validate an incoming input xmlDocument against a an existing XmlSchemaSet. Following is the code:
public class ValidateSchemas
{
private bool _isValid = true;
public List<string> errorList = new List<string>();
public bool ValidateDocument(XmlDocument businessDocument)
{
XmlSchemaSet schemaSet = SchemaLoader.Loader();
bool isValid = Validate(businessDocument, SchemaLoader._schemaSet);
return isValid;
}
public bool Validate(XmlDocument document, XmlSchemaSet schema)
{
ValidationEventHandler eventHandler = new ValidationEventHandler(HandleValidationError);
document.Schemas = schema;
document.Validate(eventHandler);
return _isValid;
}
private void HandleValidationError(object sender, ValidationEventArgs ve)
{
_isValid = false; errorList.Add(ve.Message);
}
}
The code works fine from a validation perspective. However the errorList captures only the first node error. It does not capture the other node errors. Looks like the event is getting fired only once. How to accomplish this, please help. Please note I am getting xmldocument as input , hence not using a reader.
回答1:
That's exactly the expected behavior of XmlDocument.Validate method. Once it finds a validation error it stops validate process and returns the error. So, the user has to fix that error and validate again.
This behavior is different from the Visual studio error list. For example, if you have a single syntax error in the code sometimes it returns 100s of errors. But actually you have to fix only one at one place. So, there can be both pros and cons depends on the circumstance. However, I don't think you could easily get all the validation errors for a XMLDocument, it works in a different way inherently.
来源:https://stackoverflow.com/questions/7466001/xmldocument-validate-does-not-fire-for-multiple-errors