Section 19.9. (Optional) Schema Validation with Class XmlReader


19.9. (Optional) Schema Validation with Class XmlReader

Recall from Section 19.6 that schemas provide a means for specifying XML document structure and validating XML documents. Such validation helps an application determine whether a particular document it receives is complete, ordered properly and not missing any data. In Section 19.6, we used an online XSD schema validator to verify that an XML document conforms to an XML Schema. In this section, we show how to perform the same type of validation programmatically using classes provided by the .NET Framework.

Validating an XML Document Programmatically

Class XmlReader can validate an XML document as it reads and parses the document. In this example, we demonstrate how to activate such validation. The program in Fig. 19.28 validates an XML document that the user chooseseither book.xml (Fig. 19.11) or fail.xml (Fig. 19.29)against the XML Schema document book.xsd (Fig. 19.12).

Figure 19.28. Schema-validation example.

  1  ' Fig. 19.28: FrmValidationTest.vb  2  ' Validating XML documents against schemas.  3  Imports System.Xml  4  Imports System.Xml.Schema ' contains XmlSchemaSet class  5  6       Public Class FrmValidationTest  7     Private schemas As XmlSchemaSet ' schemas to validate  against  8     Private   valid As Boolean = True ' validation result  9 10    ' handle Validate Button Click event 11    Private Sub btnValidate_Click(ByVal sender As Object, _ 12       ByVal e As EventArgs) Handles btnValidate.Click 13       schemas = New XmlSchemaSet() ' create the XmlSchemaSet class 14 15       ' add the schema to the collection 16       schemas.Add("http://www.deitel.com/booklist", "book.xsd") 17 18       ' set the validation settings 19       Dim settings As New XmlReaderSettings()         20       settings.ValidationType = ValidationType.Schema 21       settings.Schemas = schemas                      22       AddHandler settings.ValidationEventHandler, _   23          AddressOf ValidationError                    24 25       ' create the XmlReader object 26       Dim reader As XmlReader = XmlReader.Create(cboFiles.Text, settings) 27 28       ' parse the file 29       While reader.Read() 30          ' empty body 31       End While 32 33       If valid Then ' check validation result 34          lblConsole.Text = "Document is valid" 35       End If 36 37       valid = True ' reset variable 38       reader.Close() ' close reader stream 39     End Sub ' btnValidate_Click 40 41     ' event handler for validation error 42     Private Sub ValidationError(ByVal sender As Object , _ 43        ByVal arguments As ValidationEventArgs) 44        lblConsole.Text = arguments.Message 45        valid = False ' validation failed 46     End Sub ' ValidationError 47  End Class ' FrmValidationTest 

Figure 19.29. XML file that does not conform to the XML Schema document in Fig. 19.12.

  1  <?xml version = "1.0"?>  2  <!-- Fig. 19.29:  fail.xml                              -->  3  <!-- XML file that does not conform to schema  book.xsd -->  4  5  <deitel:books xmlns:deitel = "http://www.deitel.com/booklist">  6     <book>  7        <title> Visual Basic 2005 How to Program, 3/e</title>  8      </book>  9 10     <book> 11        <title> Visual  C# 2005 How to Program</title> 12     </book> 13 14     <book> 15        <title> Java How to Program, 6/e</title> 16     </book> 17 18     <book> 19        <title> C++  How to Program, 5/e</title>                        20        <title> Internet and World Wide Web How to Program, 3/e</title> 21     </book> 22 23     <book> 24        <title> XML How to Program</title> 25     </book> 26  </deitel:books> 

Line 7 declares XmlSchemaSet variable schemas. An object of class XmlSchemaSet stores a collection of schemas against which an XmlReader can validate. Line 13 assigns a new XmlSchemaSet object to variable schemas, and line 16 calls this object's Add method to add a schema to the collection. Method Add receives as arguments a namespace URI that identifies the schema (http://www.deitel.com/booklist) and the name and location of the schema file (book.xsd in the current directory).

Lines 1921 create and set the properties of an XmlReaderSettings object. Line 20 sets the XmlReaderSettings object's ValidationType property to the value ValidationType.Schema, indicating that we want the XmlReader to perform validation with a schema as it reads an XML document. Line 21 sets the XmlReaderSettings object's Schemas property to schemas. This property sets the schema(s) used to validate the document read by the XmlReader.

Lines 2223 register method ValidationError with the settings object's ValidationEventHandler. Method ValidationError (lines 4246) is called if the document being read is found to be invalid or an error occurs (e.g., the document cannot be found). Failure to register a method with ValidationEventHandler causes an exception (XmlException) to be thrown when the XML document is found to be invalid or missing.

After setting the ValidationType property, Schemas property and ValidationEventHandler of the XmlReaderSettings object, we are ready to create a validating XmlReader. Line 26 creates an XmlReader that reads the file selected by the user from the cboFiles ComboBox and validates it against the book.xsd schema.

Validation is performed node-by-node by calling method Read of the XmlReader object (line 29). Because we set XmlReaderSettings property ValidationType to ValidationType.Schema, each call to Read validates the next node in the document. The loop terminates either when all the nodes have been validated or when a node fails validation.

Detecting an Invalid XML Document

The program in Fig. 19.28 validates the XML document book.xml (Fig. 19.12) against the book.xsd (Fig. 19.11) schema successfully. However, when the user selects the XML document of Fig. 19.29, validation failsthe book element in lines 1821 contains more than one title element. When the program encounters the invalid node, it calls method ValidationError (lines 4246 of Fig. 19.28), which displays a message explaining why validation failed.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

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