我正在尝试使用回调验证事件为不成功的XML验证构建自定义错误消息。我注意到元素的sender对象是XMLReader,我从((XmlReader)sender)获得了元素或当前节点名称。来自ValidationEventargs.Exception.Message的.Name和exeception消息。我试图通过获取当前节点的父节点
来构建当前节点在验证中失败的路径以下是代码段
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.ValidationEventHandler += new ValidationEventHandler(ValidationEvent);
public void ValidationEvent(object sender, ValidationEventArgs e)
{
XmlReader xe = (XmlReader)sender;
ValidationError ve = new ValidationError();
ErrorElement = xe.Name;
ErrorMessage = e.Exception.Message;
ErrorPath = ""\\want to build the Node path
}
答案 0 :(得分:1)
根据此thread,您需要使用XmlDocument.Validate。这是我的代码:
private static void ValidationErrorHandler(object sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
{
string offendingElementName = BuildQualifiedElementName((e.Exception as XmlSchemaValidationException));
// meaningful validation reporting code goes here
Console.Out.WriteLine("{0} is invalid", offendingElementName);
}
}
private static string BuildQualifiedElementName(XmlSchemaValidationException exception)
{
List<string> path = new List<string>();
XmlNode currNode = exception.SourceObject as XmlNode;
path.Add(currNode.Name);
while (currNode.ParentNode != null)
{
currNode = currNode.ParentNode;
if (currNode.ParentNode != null)
{
path.Add(currNode.Name);
}
}
path.Reverse();
return string.Join(".", path);
}