Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronous XML Schema Validation? .NET 3.5

I know I can validate xml against a schema using a callback method like the following, but is there a way that I can do it synchronously instead of event driven?

One way I thought of would be to set a class member boolean flag IsValidated=false then
call xml.Validate(ValidationEventHandler). The event handler would set IsValidated=true once it's finished. In the mean time, do a loop checking until the flag is set to true then continue.

This is for .Net 3.5.

    public bool ValidateSchema(string xmlPath, string xsdPath)
    {
        XmlDocument xml = new XmlDocument();
        xml.Load(xmlPath);

        xml.Schemas.Add(null, xsdPath);

        xml.Validate(ValidationEventHandler); 
    }

Ok, I have done a test and it appears that xml.validate actually waits until the callback has completed before new code is executed.

In the following example, the MessageBox.Show("After Validate"); always happens after the execution of myValidationEventHandler.

I also stepped through the code to verify this.

So I guess that makes my question a non issue.

// load etc.
...

xmlValidate(myValidationEventHandler);

MessageBox.Show("After Validate");


    private void myValidationEventHandler(object sender, ValidationEventArgs e)
    {
        for (double i = 0; i < 100000; i++)
        {
            textBox1.Text = i.ToString();
            Application.DoEvents();
        }

    // do stuff with e
    }
like image 869
M3NTA7 Avatar asked Oct 10 '11 21:10

M3NTA7


1 Answers

You can specify null for the ValidationEventHandler to have the Validate method throw an exception.

    public bool ValidateSchema(string xmlPath, string xsdPath)
    {
        XmlDocument xml = new XmlDocument();
        xml.Load(xmlPath);

        xml.Schemas.Add(null, xsdPath);

        try
        {
            xml.Validate(null);
        }
        catch (XmlSchemaValidationException)
        {
            return false;
        }
        return true;
    }
like image 111
Timiz0r Avatar answered Sep 28 '22 10:09

Timiz0r