How to get invalid XMLNode in XmlReaderSettings.Va

2019-08-01 16:14发布

问题:

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:

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