XML Schema Validation Issues

DUH-mainWorking on one of our long term projects recently I came across a gotcha that I have never encountered before when working with Xml Schema documents. Whilst researching and correcting this issue I have subsequently seen a lot of other people making the same mistake on many other forums and so I thought I should share.

The issue arose when I had a loaded Xml document that I subsequently wished to validate against a schema that we have defined, fine I thought, I will use the following code….

 

public void validateResponseXML(XmlDocument doc, SchemaRow schemaRow) {
    doc.Schemas.Add(null, schemaRow.SchemaLocation);
    xmlValidationErrors.Clear();
    doc.Validate(onValidateFile);

    if (xmlValidationErrors.Count > 0) {
        ……. etc
    }
}

I then threw an invalid xml file at this validation routine….Odd….. this code did not pick up the validation exceptions I expected to encounter. After a little research I refactored creating another routine that did work,  this however used a slightly different approach as detailed below.


public void validateResponseXML(XmlDocument doc, SchemaRow schemaRow) {

XmlTextReader schemaReader = new XmlTextReader(schemaRow.SchemaLocation);
XmlSchema schema = XmlSchema.Read(schemaReader, null);
doc.Schemas.Add(schema);
xmlValidationErrors.Clear();
doc.Validate(onValidateFile);

if (xmlValidationErrors.Count > 0) {
....... etc
}
}

Whilst this approach worked flawlessly I was curious as to why the two routines behaved differently, examining the in memory objects I noticed a property entitled IsCompiled against the schema objects, this struck me as the values of this property were different for each of the two approaches. It was at the same time that I found another article with someone else experiencing this issue and a responder saying ‘Duh! Have you compiled the schemas?'(I’m paraphrasing!)

Duh indeed….The answer it seems was simple but a subtlety that I had not appreciated. I refactored my original code to the snippet below.

public void validateResponseXML(XmlDocument doc, SchemaRow schemaRow) {

    doc.Schemas.Add(null, schemaRow.SchemaLocation);
    doc.Schemas.Compile();
    xmlValidationErrors.Clear();
    doc.Validate(onValidateFile);

    if (xmlValidationErrors.Count > 0) {
        ……. etc
    }
}

Now, hey presto, when the code is re-compiled and run against an invalid xml file the schema validation behaves exactly as you would expect. This won’t change anyone’s life, but it may save a few hours of head scratching.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s