C# 如何知道验证失败的xml文件

C# 如何知道验证失败的xml文件,c#,xml,validation,xsd,C#,Xml,Validation,Xsd,我有以下代码来验证我的xml: private bool ValidateXML(string filePath) { try { XmlDocument xmld = new XmlDocument(); xmld.Load(filePath); xmld.Schemas.Add(null, @"C:\...\....xsd"); xmld.Validate(ValidationEventHandler);

我有以下代码来验证我的xml:

private bool ValidateXML(string filePath)
{
    try
    {
        XmlDocument xmld = new XmlDocument();
        xmld.Load(filePath);
        xmld.Schemas.Add(null, @"C:\...\....xsd");
        xmld.Validate(ValidationEventHandler);
        return true;
    }
    catch
    {
        return false;
    }
}

static void ValidationEventHandler(object sender, ValidationEventArgs e)
{
    switch (e.Severity)
    {
        case XmlSeverityType.Error:
            Debug.WriteLine("Error: {0}", e.Message);
            break;
        case XmlSeverityType.Warning:
            Debug.WriteLine("Warning {0}", e.Message);
            break;
    }
}

但是,当我在回拨时,我如何知道失败文件的文件路径?我想将其移动到一个“失败”文件夹,但不知道它是哪一个,我无法执行。

如果文件路径失败,可以返回文件路径,如果通过,则返回空字符串,而不是返回bool。或者类似的方法。

您可以使用匿名方法,这样您的“file”变量就可以被“捕获”,这样您就可以在
ValidationEvent
回调中使用它

    public static bool ValidateXmlFile1(string filePath, XmlSchemaSet set)
    {
        bool bValidated = true;

        try
        {
            XmlDocument tmpDoc = new XmlDocument();

            tmpDoc.Load(filePath);

            tmpDoc.Schemas = set;

            ValidationEventHandler eventHandler = new ValidationEventHandler(
                (Object sender, ValidationEventArgs e) =>
                {
                    switch (e.Severity)
                    {
                        case XmlSeverityType.Error:
                            {
                                Debug.WriteLine("Error: {0} on file [{1}]", e.Message, filePath);

                            } break;

                        case XmlSeverityType.Warning:
                            {
                                Debug.WriteLine("Error: {0} on file [{1}]", e.Message, filePath);

                            } break;
                    }

                    bValidated = false;
                }
            );

            tmpDoc.Validate(eventHandler);
        }
        catch
        {
            bValidated = false;
        }

        return bValidated;
    }

sender
对象是什么类型?也许你可以从那里检索一些信息……也许更应该这样:@marsze谢谢你的评论解决了这个问题,我所需要的只是在回调方法中抛出一个错误。