A simple way to validate XML against a schema is to use XPathNavigator.CheckValidity(), which is new for 2.0. If the XML is valid, the function returns true, otherwise false, by means of an exception. At the time I wrote this, I actually could find nothing via Google to show me how to implement this, other than the Visual Studio 2005 Documentation, which is pre-release documentation and subject to change. As a result, I have decided to show my code here, while quite simple, to give an example for those looking for one.
In order to check the validity of our XML in our XPathDocument against a schema, we need to set up the appropriate objects to handle this.
CheckValidity requires an XmlSchemaSet and a ValidationEventHandler. public virtual bool CheckValidity(XmlSchemaSet schemas, ValidationEventHandler validationEventHandler);
XmlSchemaSet is also new for 2.0, and has been introduced to fix a number of issues, including standards compatibility, performance, and the obsolete Microsoft XML-Data Reduced (XDR) schema format. In my example, I only want to validate my XML against one schema. I must use the XmlSchema class in order to load my customized schema. I then add my schema to my XmlSchemaSet to use for validation. Of course there are other ways to validate XML against an XSD, so do what you wish.
The second part of CheckValidity is the ValidationEventHandler that receives information about schema validation warnings and errors. I recommend not setting this null, and processing the errors should they arise.
Assuming we already have an XPathDocument and an XPathNavigator created, we have the following.
// Create an event handler to trap Validation errors.ValidationEventHandler validationHandler = new ValidationEventHandler(XmlValidationError);// Create XmlSchemaSet and XmlSchemaXmlSchemaSet set = new XmlSchemaSet();XmlSchema schema = XmlSchema.Read(new XmlTextReader(@"C:\Temp\MySchema.xsd"), validationHandler);// Add our schema to the XmlSchemaSetset.Add(schema);// Now we can validateif (!xpathNavigator.CheckValidity(set, validationHandler)) // invalid - do somethingelse // valid - do something}// Define our event handler outside the scope of this code// Handles XML Validation errors.static void XmlValidationError(object sender, ValidationEventArgs ex){ throw new XmlSchemaValidationException(ex.Message);}
One note, we really do not need to create a new instance of our ValidationEventHandler. We could pass null into our XmlSchema.Read() and create a new reference to our event handler in our CheckValidity() function.
Again, there are a number of ways to validate your XML against an XSD. In my case, I was working with the XPathDocument and XPathNavigator objects. I decided to take advantage of the XPathNavigator.CheckValidity() method new in the 2.0 framework.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2009 MuellerDesigns.net
Sign In