How to get invalid XMLNode in XmlReaderSettings.Va

2019-08-01 16:33发布

I am trying to construct a custom Error Message for unsuccessful XML validation using the callback validation event. I noticed that the sender object of the element is XMLReader and i got the Element or current Node name from ((XmlReader)sender).Name and exeception message from ValidationEventargs.Exception.Message. I trying to build the path of the current node failing in the validation by getting the parent nodes of the current node

Given below is the code snippet

                  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
                  }

1条回答
霸刀☆藐视天下
2楼-- · 2019-08-01 17:13

As per this thread, You need to use XmlDocument.Validate instead. Here's my code:

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);
}
查看更多
登录 后发表回答