0

我有这段代码来验证我的 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;
    }
}

但是当我在回调中时,我怎么知道失败文件的文件路径?我想将它移动到“失败”文件夹,但我不知道它是哪一个。

4

2 回答 2

0

You could use an anonymous method so that your "file" variable can get "captured" so you can use it inside the ValidationEvent callback.

    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;
    }
于 2013-07-19T14:04:42.290 回答
0

如果失败,您可以返回文件路径,如果通过,则返回空字符串,而不是返回布尔值。或类似的东西。

于 2013-07-19T13:51:06.060 回答