13.5 Validating XML Documents with Schemas

 <  Day Day Up  >  

You want to ensure an XML file is valid by testing it against a defined schema.


Technique

You validate an XML document by using the XmlValidatingReader class instead of XmlTextReader or XmlNodeReader . However, the XmlValidatingReader only validates the data that is being read and delegates the actual loading and parsing of the XML file to one of the other classes. To create an XmlValidatingReader object that will read from an XML file, create an XmlTextReader or XmlNodeReader object and pass it into the XmlValidatingReader constructor:

 
 XmlTextReader xmlTR = new XmlTextReader( currentDoc ); XmlValidatingReader xmlVR = new XmlValidatingReader( xmlTR ); 

Validation utilizes events rather than exceptions to report any validation errors. It allows you to continue parsing the document even if a portion of it is invalid, thereby allowing you to notify the user of all validation errors that were encountered . The event that is fired is named appropriately enough ValidationEventHandler , and the delegate accepts a ValidationEventArgs object in addition to the standard System.Object representing the sender of the event. Combining these facts with the code shown earlier, setting up validation appears as follows :

 
 private void mnuValidate_Click(object sender, System.EventArgs e) {     ValidateOpen vo = new ValidateOpen();     if( vo.ShowDialog(this) == DialogResult.OK )     {         // load document         XmlTextReader xmlTR = new XmlTextReader( currentDoc );         XmlValidatingReader xmlVR = new XmlValidatingReader( xmlTR );         xmlVR.ValidationEventHandler +=             new ValidationEventHandler (SchemaValidationHandler);         while( xmlVR.Read() )         {             // process XML         }         xmlVR.Close();     } } public void SchemaValidationHandler(object sender, ValidationEventArgs args) {     string error = "*** Validation Failed ***\n";     error += args.Message;     MessageBox.Show( this, error, "XML Viewer",         MessageBoxButtons.OK, MessageBoxIcon.Error ); } 

Comments

Because XML files can come in all shapes and sizes, schemas define a certain XML file format that you can validate generated XML files against. The XML schema language itself can be difficult to understand, which is why several books exist just on that single topic. In most cases, however, you can utilize one of the many XML tools and even Visual Studio .NET to automatically generate a schema based on an existing XML file. To do so using Visual Studio .NET, open an XML file and click on XML, Create Schema from the main menu. Although this method works for most XML files that you deal with, sometimes you will have to hand-edit the schema so that it better fits your XML file format.

Once you define an XML schema for your XML file format, you can use it to validate XML files that are created off that schema. When you use the XmlValidatingReader class in the .NET Framework, you have two options available to associate a schema with an XML document. There is no clear-cut best practice with using any option, so you should therefore pick the option that more closely fits with your project's design objectives.

One of these options is to simply place a reference to the schema file within the XML file itself. For instance, to associate a schema file named XMLSchema.xsd located in the same file directory as an XML file that uses that schema, the XML file makes a reference at the root element as follows:

 
 <?xml version="1.0" encoding="utf-8"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:noNamespaceSchemaLocation="XMLSchema.xsd"/> 

When you use the XmlValidatingReader class to parse the XML file, the ValidationEventHandler fires whenever the XML file doesn't conform to the schema it references.

One other option is to programmatically add a schema reference before parsing begins. You do so by accessing the Schemas collection defined in the XmlValidatingReader . The Schemas collection contains an Add method that allows you to either add an entire prebuilt collection or specify a filename to the xsd file. Once you do so, validation occurs even if there is no schema referenced within the original XML file:

 
 xmlVR.Schemas.Add( null, vo.Path ); while( xmlVR.Read() ){} xmlVR.Close(); 
 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net