如何在 C# 中的 XmlReaderSettings.ValidationEventHandler 中获取无效的 XMLNode [英] How to get invalid XMLNode in XmlReaderSettings.ValidationEventHandler in C#

查看:21
本文介绍了如何在 C# 中的 XmlReaderSettings.ValidationEventHandler 中获取无效的 XMLNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用回调验证事件为不成功的 XML 验证构建自定义错误消息.我注意到元素的发送者对象是 XMLReader,我从 ((XmlReader)sender).Name 和 ValidationEventargs.Exception.Message 中获得了元素或当前节点名称.我试图通过获取当前节点的父节点来构建验证失败的当前节点的路径

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

下面是代码片段

                  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
                  }

推荐答案

根据此 线程,您需要使用 XmlDocument.Validate 代替.这是我的代码:

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

这篇关于如何在 C# 中的 XmlReaderSettings.ValidationEventHandler 中获取无效的 XMLNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆